如何检查我的迭代器是否一无所获

时间:2010-09-04 21:04:00

标签: c++ iterator multimap

我正在使用多图stl,我迭代我的地图,我没有在地图中找到我想要的对象,现在我想检查我的迭代器是否包含我想要的东西,我遇到了困难用它,因为它不是null或其他东西。感谢名单!

2 个答案:

答案 0 :(得分:8)

如果找不到你想要的东西,那么它应该等于容器的end()方法返回的迭代器。

所以:

iterator it = container.find(something);
if (it == container.end())
{
  //not found
  return;
}
//else found

答案 1 :(得分:0)

为什么要在你的地图上迭代找东西,你应该像ChrisW一样在你的地图中找到一把钥匙......

嗯,你想找到地图中的价值而不是钥匙吗?然后你应该这样做:

map<int, string> myMap;
myMap[1] = "one"; myMap[2] = "two"; // etc.

// Now let's search for the "two" value
map<int, string>::iterator it;
for( it = myMap.begin(); it != myMap.end(); ++ it ) {
   if ( it->second == "two" ) {
      // we found it, it's over!!! (you could also deal with the founded value here)
      break; 
   }
}
// now we test if we found it
if ( it != myMap.end() ) {
   // you also could put some code to deal with the value you founded here,
   // the value is in "it->second" and the key is in "it->first"
}