找到后stl容器端是多余的,那么快捷方式是什么

hig*_*dth -1 c++ stl

让我们假设我们有一个地图类(无序地图,列表,集合,也可以做任何事情).我们正在寻找一个特定的元素.在调用find()成员之后,我们必须检查end()成员.但是find()在内部已经知道它是返回一个好的迭代器还是结束迭代器.我们为什么还需要再次调用end()?这增加了一些开销.

std::map<int,float> myMap;
// some other code to populate the map
// ...
std::map<int,float>::iterator myIt;
myIt = myMap.find(2); // doesn't this already know wheter its returning the end() iterator?
if (myIt != myMap.end()) { //calling end() here wastes some time because find
                           //already knew the result
   std::cout << "Found, value is "<<(*myIt).second<<"\n";
} else {
   std::cout << "Not found.\n";
}
Run Code Online (Sandbox Code Playgroud)

应该有一种方法可以在不调用end()的情况下知道find()的结果.

cas*_*nca 7

还有什么可能回归?它需要返回一个有效的迭代器,但除了end()引用容器中的实际元素之外的任何东西.这里真的没有选择.

此外,STL函数end()通常是内联的,并且在编译器之上进行了相当多的优化,因此额外的调用并不是真正的调用.

  • @user:没有优化的分析完全没有意义. (3认同)