stl - C++.How output elements from std::set in format "(element, element, element)" without last ", "? -
this question has answer here:
- printing lists commas c++ 23 answers
when using std::list, have method "back()":
for ( = list->begin(); != list.back(); it++ ) { cout << it.getname() << ", "; } cout << it.getname() << endl;
output: (element, element, element)
std::set has no member back(), , can't output last element without ", ":
output: (element, element, element, )
this enough uses:
for (auto = list.begin(); != list.end(); ++it) { if (it != list.begin()) cout << ", "; cout << it->getname(); }
if want (
)
around output, add cout
s either side of loop.
if you're mad-keen keep conditional out of loop:
if (!list.empty()) { auto = list.begin(); cout << it->getname(); while (++it != list.end()) cout << ", " << it->getname(); }
Comments
Post a Comment