map find()函数,如果所需的键在最后一个位置



我是C++初学者。我知道find()是用来搜索某个密钥的。如果找到元素,此函数将向该元素返回一个迭代器,否则它将返回一个指向的最后位置的迭代器。映射,即CCD_ 2。我从网站上看到

if(it == mp.end())
cout << "Key-value pair not present in map" ;
else
cout << "Key-value pair present : "

如果找到的钥匙在最后位置怎么办?它怎么还能工作?键按一定的顺序排序,我认为迭代器遍历排序后的键来找到我们想要的键。(正确吗?(

stl中所有.end()的结果都超出了有效值。所以end((永远不会有效。

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++ ) {
}

因此,让我们用矢量习惯用法重写数组

for( auto i = 0; &arr[i] != &arr[10]; i++ ){
}

映射更复杂,它们有不同的保护机制,但迭代器==end()从来都不是有效的。

根据cplusplus.com,.end()Returns an iterator pointing to the past-the-end element in the sequence:

它不指向容器中的元素(在您的情况下是映射(,而是指向容器外部

最新更新