Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the element is the first or the last one in an std::vector

I have the following for each C++ code:

for (auto item : myVector) {     std::cout << item;      if (item == orderBy.IsLast())       // <--- Check if this is the last element         std::cout << "(Is last element) " << std::endl;     else if (item == orderBy.IsFirst()) // <-- Check if this is the first element         std::cout << "(Is first element)" << std::endl; } 

Of course IfLast() and IfFirst() do not exist on std::vector. Is there a native std:: way to check for first and last element ?

like image 880
Mendes Avatar asked May 13 '15 03:05

Mendes


People also ask

How do I find the first element of a vector?

vector::front() This function can be used to fetch the first element of a vector container.

How do you find something in a vector C++?

You can use the find function, found in the std namespace, ie std::find . You pass the std::find function the begin and end iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.


1 Answers

You shouldn't use the range-based for in this case, as this kind of for "hides" the iterator, and you'd need an additional counter to keep track of the position in vector. You can simply do

for(auto it = myVector.begin(); it != myVector.end(); ++it) {     if(it == myVector.begin()) // first element     {         // do something     }     else if(std::next(it) == myVector.end()) // last element     {         // do something else     } } 

Note that simply comparing my.Vector.back() with your element from a range-based for is OK only if you're sure that you don't have duplicates in the vector. But if e.g. the value of the last element appears multiple times in the vector, you're going to find only its first position. So that's why there's really no good way of using a range-based for without an additional index that keeps track of where exactly in the vector you are.

EDIT See also @thelink2012's answer for how to "trick" your range-based for so you can get the position of the element implicitly.

like image 105
vsoftco Avatar answered Sep 21 '22 22:09

vsoftco