Mathias Soeken
Mathias Soeken

Reputation: 1303

Creating a prefixed sequence in one line

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

Upvotes: 3

Views: 396

Answers (6)

kennytm
kennytm

Reputation: 523224

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);
}

Upvotes: 1

Manuel
Manuel

Reputation: 13099

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));

Upvotes: 3

Alexander Smirnov
Alexander Smirnov

Reputation:

BOOST_FOREACH(std::string & str, strings) str = "x" + boost::lexical_cast<std::string>(a++);

Upvotes: 1

Pete Kirkham
Pete Kirkham

Reputation: 49311

#define IM_NOT_A_SEMICOLON_REALLY ; then proceed at will.

Upvotes: 6

f4.
f4.

Reputation: 3852

a derivate of UncleBen's answer but using only the STL

while( a < b ) vStrings.push_back( 'x' + ( (std::stringstream&)( std::stringstream() << a++ ) ).str() );

Upvotes: 3

UncleBens
UncleBens

Reputation: 41331

What a challenge!

while (a < b) strings.push_back('x' + boost::lexical_cast<std::string>(a++));

Also, compare verbosity with Manuel's answer :)

Upvotes: 8

Related Questions