Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if I'm on the last element when iterating using foreach syntax [duplicate]

Tags:

c++

foreach

c++11

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(", "); } 
like image 528
Llamageddon Avatar asked Dec 20 '14 22:12

Llamageddon


People also ask

How do I find the last iteration of foreach?

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.

How do you get the last element in a for loop C++?

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.


1 Answers

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(", ");     // ... } 
like image 170
Barry Avatar answered Oct 01 '22 01:10

Barry