Given the initialized variables unsigned a
, unsigned b
with b > a
and std::vector<std::string> strings
of size b-a
. How can I fill strings
with the elements e.g. "x3" "x4" "x5" "x6"
(in case a=3
and b=7
) for arbitrary a
and b
with one C++ command (meaning one semicolon at all :))?
views:
277answers:
6
+1
A:
BOOST_FOREACH(std::string & str, strings) str = "x" + boost::lexical_cast<std::string>(a++);
I see you have reverted my change to `lexical_cast<string>(a++)`. Where in the reference (or in C++ in general) does it say that the template argument for a function can be deduced for the return type? All I get is: "no matching function for call to 'lexical_cast(int)'"
UncleBens
2010-02-16 23:23:32
I'm sorry, u were right.
2010-02-17 11:01:16
+3
A:
Not too challenging...
std::transform(
boost::make_counting_iterator(a), boost::make_counting_iterator(b),
strings.begin(),
"x" + boost::lambda::bind(boost::lexical_cast<std::string, unsigned int>,
boost::lambda::_1));
Manuel
2010-02-16 20:06:46
+1 Probably the intended answer if you are not supposed to modify `a`. But would you seriously use something like this in practice?
UncleBens
2010-02-16 22:33:39
I don't think it's so bad, I've seen people abuse `boost::lambda` in much worst ways. But yes, in this case a simple for loop would be simpler to write and more readable.
Manuel
2010-02-16 22:39:34
Since `strings` in the example is already preinitialized, a `strings.begin()` would be more suitable and correct, but anyway this is easier than an approach with boost.bind I tried. I like the STL way of doing this, but the `while` loop is a nice answer to see that sometimes it is easy not to see the _easy_ way anymore :)
Rupert Jones
2010-02-16 22:58:42
+7
A:
What a challenge!
while (a < b) strings.push_back('x' + boost::lexical_cast<std::string>(a++));
Also, compare verbosity with Manuel's answer :)
UncleBens
2010-02-16 20:51:31
+3
A:
a derivate of UncleBen's answer but using only the STL
while( a < b ) vStrings.push_back( 'x' + ( (std::stringstream&)( std::stringstream() << a++ ) ).str() );
f4
2010-02-16 23:07:26
+1
A:
Abusing comma operators, which are obviously not semicolons:
while (a<b) {
char s[12],
t = (snprintf(s, 11, "x%d", a++), strings.push_back(s), 0);
}
KennyTM
2010-02-17 12:13:10