tags:

views:

277

answers:

6

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 :))?

+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
I'm sorry, u were right.
+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
+1 Probably the intended answer if you are not supposed to modify `a`. But would you seriously use something like this in practice?
UncleBens
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
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
@Rupert - thanks, fixed
Manuel
+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
+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
+5  A: 

#define IM_NOT_A_SEMICOLON_REALLY ; then proceed at will.

Pete Kirkham
nice one :) ...
f4
+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