如何检查我的迭代器是否没有任何东西

发布于 2024-09-17 21:21:43 字数 95 浏览 7 评论 0原文

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

i'm using a multimap stl, i iterate my map and i did'nt find the object i wanted inside the map, now i want to check if my iterator holds the thing i wanted or not and i'm having difficulties with it because it's not null or something. thanx!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

人心善变 2024-09-24 21:21:43

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

所以:

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

If it doesn't find the thing you want then it should equal the iterator returned by the end() method of the container.

So:

iterator it = container.find(something);
if (it == container.end())
{
  //not found
  return;
}
//else found
也只是曾经 2024-09-24 21:21:43

为什么你要迭代你的地图来寻找某些东西,你应该像 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"
}

Why are you iterating over your map to find something, you should go like ChrisW to find a key in your map...

Mmm, are you trying to find the value in your map and not the key? Then you should do:

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"
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文