如何查找std :: map中是否存在元素?

yeg*_*256 55 c++

我的用例:

map<string, Car> cars;
bool exists(const string& name) {
  // somehow I should find whether my MAP has a car
  // with the name provided
  return false;
} 
Run Code Online (Sandbox Code Playgroud)

能否请您用C++建议最好和最优雅的方式?谢谢.

ken*_*ytm 74

return cars.find(name) != cars.end();
Run Code Online (Sandbox Code Playgroud)


Tom*_*Tom 60

当然,使用迭代器

map<string,Car>::const_iterator it = cars.find(name);
return it!=cars.end();
Run Code Online (Sandbox Code Playgroud)

  • 有没有理由为什么C++没有像"cars.exists(name)"这样的东西?使用find生成详细代码. (10认同)
  • 既然你没有改变`cars`,最好得到一个`const_iterator`. (5认同)
  • 为什么不跳过临时而不用担心:`cars.find(name)!= cars.end()`? (4认同)
  • @QuentinPratet:它不需要.exists(),因为它有.count(),它更强大,同样简洁.(我的回答中的例子) (2认同)

Joh*_*itb 25

你也可以用

bool exists(const string& name) {
  return cars.count(name) != 0;
} 
Run Code Online (Sandbox Code Playgroud)

  • @Potatoswatter但确切地说明了测试的内容.它纯粹是一个风格问题,但我倾向于不依赖于隐式int来布尔转换. (14认同)
  • @Potatoswatter:显式比较会抑制VC++警告("性能警告:强制整数到bool");) (5认同)

foo*_*foo 20

除了来自find()的iterator-Value和与.end()的比较之外,还有另一种方法:map :: count.

您可以使用特定键调用map :: count(key); 它将返回给定键存在的条目数.对于具有唯一键的地图,结果将为0或1.由于多图也存在相同的界面,因此为了安全起见,最好与!= 0进行比较.

就你的例子而言,那是

return (cars.count(name)>0);
Run Code Online (Sandbox Code Playgroud)

我看到的优点是1.更短的代码,2.利用其表示细节,可以从库内部应用的任何优化中受益.


D.S*_*ley 8

关于什么:

template <typename KeyType, typename Collection>
bool exists_in(Collection const& haystack, KeyType const& needle) {
    return std::find(haystack.begin(), haystack.end(), needle) != haystack.end();
}

template <typename K, typename V>
bool exists_in(std::map<K,V> const& haystack, K const& needle) {
    return haystack.find(needle) != haystack.end();
}
Run Code Online (Sandbox Code Playgroud)

这使得exists_in可以使用任何标准容器std::find并使用特殊版本,std::map因为它提供了更有效的搜索替代方案.您可以根据需要添加其他专业化(例如,用于std::set和其他).

  • 通过const引用传递所有内容. (4认同)

Mik*_*our 5

bool exists(const string& name)
{
    return cars.find(name) != cars.end();
}
Run Code Online (Sandbox Code Playgroud)