Use the std::vector::front
and std::vector::back
to get a reference to the data in the first and last positions.
Reference is a keyword here because you could efficiently check the address of your iterating item
and the address of the respective front/back references. In your example you take the item
by value not reference so this prehaps wouldn't work, take in consideration this example that'd work with this method:
for(auto& item : myVector) // take item by reference
{
std::cout << item;
if (&item == &myVector.back())
std::cout << "(last element) " << std::endl;
else if (&item == &myVector.front())
std::cout << "(first element)" << std::endl;
}
If the object overloads the address of operator &
(though it's considered a bad practice) you might want to use std::addressof
instead.
This method won't work however for the std::vector<bool>
specialization since it optimizes the vector to store booleans efficiently with bits, and since we cannot have references to bits, all references taken out this data structure is a proxy object not exactly tied to the address of the internal data.