我的用例:
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++建议最好和最优雅的方式?谢谢.
Tom*_*Tom 60
当然,使用迭代器
map<string,Car>::const_iterator it = cars.find(name);
return it!=cars.end();
Run Code Online (Sandbox Code Playgroud)
Joh*_*itb 25
你也可以用
bool exists(const string& name) {
return cars.count(name) != 0;
}
Run Code Online (Sandbox Code Playgroud)
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.利用其表示细节,可以从库内部应用的任何优化中受益.
关于什么:
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
和其他).
bool exists(const string& name)
{
return cars.find(name) != cars.end();
}
Run Code Online (Sandbox Code Playgroud)