Reputation: 1303
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
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
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
Reputation:
BOOST_FOREACH(std::string & str, strings) str = "x" + boost::lexical_cast<std::string>(a++);
Upvotes: 1
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
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