c++ - How to nicely output a list of separated strings? -
usually, when had display list of separated strings, doing like:
using namespace std; vector<string> mylist; // lets consider has 3 elements : apple, banana , orange. (vector<string>::iterator item = mylist.begin(); item != mylist.end(); ++item) { if (item == mylist.begin()) { cout << *item; } else { cout << ", " << *item; } }
which outputs:
apple, banana, orange
i discovered std::ostream_iterator
if found nice use.
however following code:
copy(mylist.begin(), mylist.end(), ostream_iterator<string>(cout, ", "));
if get:
apple, banana, orange,
almost perfect, except ,
. there elegant way handle special "first (or last) element case" , have same output first code, without "complexity" ?
although not std:
cout << boost::algorithm::join(mylist, ", ");
edit: no problem:
cout << boost::algorithm::join(mylist | boost::adaptors::transformed(boost::lexical_cast<string,int>), ", " );
Comments
Post a Comment