C++ 检查C+中是否存在元素+;地图?
可能重复:C++ 检查C+中是否存在元素+;地图?,c++,dictionary,stl,C++,Dictionary,Stl,可能重复: 在C++中,如何检查有键的元素是否存在? if (myMap.find(key) != myMap.end()) { // there is such an element } 请参阅forstd::map::find尝试使用find方法查找它,如果未找到元素,该方法将返回映射的end()迭代器: if (data.find(key) != data.end()) { // key is found } else { // key is not found }
在C++中,如何检查有键的元素是否存在?
if (myMap.find(key) != myMap.end())
{ // there is such an element
}
请参阅for
std::map::find
尝试使用find
方法查找它,如果未找到元素,该方法将返回映射的end()
迭代器:
if (data.find(key) != data.end()) {
// key is found
} else {
// key is not found
}
当然,如果以后需要与给定键对应的值,则不应该两次查找。在这种情况下,只需先存储find
的结果:
YourMapType data;
...
YourMapType::const_iterator it;
it = data.find(key);
if (it != data.end()) {
// do whatever you want
}
@空间:几乎没有。了解一个键和一个值之间的区别。实际上,这个问题的标题是误导性的,它实际上是关于找出一个给定的键是否存在于一个std::map中。@Tomalak:重新阅读这个问题和所有答案后,我有理由相信它是重复的。虽然标题不准确。+1(尽管我不会向语言新手推荐cplusplus.com)。@Tomalak Geret'kal:你确定OP是新手吗?你会推荐什么呢?我很好奇,cplusplus有什么不好的地方?我经常用它来理解一些小的东西。这个问题反而泄露了它。@RickoM:cplusplus.com是出了名的错误百出,而且它的教程有误导性(即使是教程)。我自己用它作为“提醒”的参考,但是我知道C++足够好发现错误,绝对不会推荐它。