For example:
for( auto &iter: item_vector ) { if(not_on_the_last_element) printf(", "); }
or
for( auto &iter: skill_level_map ) { if(not_on_the_last_element) printf(", "); }
Method 1: It is the naive method inside foreach loop to find iteration. Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration.
To get the last element in an iterator loop you can use std::next() (from C++11). The loop is generally terminated by iterator != container. end() , where end() returns an iterator that points to the past-the-end element.
You can't really. That's kind of the point of range-for, is that you don't need iterators. But you can just change your logic on how you print your comma to print it if it's not first:
bool first = true; for (auto& elem : item_vector) { if (!first) printf(", "); // print elem first = false; }
If that's the intent of the loop anyway. Or you could compare the addresses:
for (auto& elem : item_vector) { if (&elem != &item_vector.back()) printf(", "); // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With