Reputation: 1
I am a C++ beginner. I know that find()
is used to search for a certain key. This function returns an iterator to the element if the element is found, else it returns an iterator pointing to the last position of the. map i.e map.end()
.
I read from websites that
if(it == mp.end())
cout << "Key-value pair not present in map" ;
else
cout << "Key-value pair present : "
What if the found key is in the end postition? How can it still work? Key is sorted in a certain order and I think the iterator traverses the sorted key to find the one we want. (is it correct?)
Upvotes: 0
Views: 76
Reputation: 25
According to cplusplus.com , .end()
Returns an iterator pointing to the past-the-end element in the sequence:
It does not point to an element in the container ( the map in your case ), rather points outside of it.
Upvotes: 1
Reputation: 13073
The result of all .end()
in the stl is beyond the valid values. So end() will never be valid.
int arr[10];
// arr has valid indices 0,1,2,3,...,7,8,9
// arr[10] is not valid.
for( auto i = 0; i < 10; i++ ){
}
std::vector vec;
vec.resize( 10 );
// vec.end() is equivalent to arr[10] - not part of the vector
for( auto it = vec.begin(); vec != vec.end(); vec++ ) {
}
So lets re-write the array in the vector idiom
for( auto i = 0; &arr[i] != &arr[10]; i++ ){
}
Maps are more complicated, they have a different guard mechanism, but an iterator == end()
never is valid.
Upvotes: 1