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 ?
vector::front() This function can be used to fetch the first element of a vector container.
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.
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.
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