我的使用情況:如何查找std :: map中是否存在元素?
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;
}
能否請您建議最好的和最優雅的方式做到這一點在C++?謝謝。
我的使用情況:如何查找std :: map中是否存在元素?
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;
}
能否請您建議最好的和最優雅的方式做到這一點在C++?謝謝。
當然,使用迭代器
map<string,Car>::const_iterator it = cars.find(name);
return it!=cars.end();
bool exists(const string& name)
{
return cars.find(name) != cars.end();
}
如果它是一個成員,使函數'const'? – 2010-05-06 14:41:11
如果是會員,那麼是的。 – 2010-05-06 14:42:47
return cars.find(name) != cars.end();
這是我會用的答案! – 2015-03-19 14:21:18
bool exists(const std::map<std::string, Car>& cars, const std::string& name) {
return cars.end() != cars.find(name);
}
爲什麼不通過使它成爲模板函數來使它更通用?但它可能不會滿足優雅的要求更好.. – foraidt 2010-05-06 15:01:17
@mxp,請參閱我的解決方案(http://stackoverflow.com/questions/2781899/how-to-find-whether-an-element-exists -in-stdmap/2782084#2782084)。 – 2010-05-06 15:04:31
std::map::find(const key_type& x);
如果該項目不存在,它返回map::end
。
你也可以使用
bool exists(const string& name) {
return cars.count(name) != 0;
}
'!= 0'可選。 – Potatoswatter 2010-05-06 15:31:39
@Patatoswatter但是清楚地說明了正在測試的內容。它純粹是一個風格問題,但我傾向於不依賴隱式int來布爾轉換。 – KeithB 2010-05-06 15:51:05
@Potatoswatter:明確的比較將抑制VC++警告(「性能警告:強制整數爲bool」);) – UncleBens 2010-05-06 16:05:42
什麼:
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();
}
這使得與任何標準集裝箱exists_in
工作通過std::find
,並使用一個特殊的版本std::map
,因爲它提供了一個更有效的搜索替代。您可以根據需要添加其他專業化(例如,std::set
等)。
通過const引用傳遞所有內容。 – UncleBens 2010-05-06 16:07:18
除了find()中的iterator-Value和與.end()的比較,還有另一種方法:map :: count。
你可以用特定的鍵調用map :: count(key)它會返回給定密鑰的條目數量。對於具有唯一鍵的映射,結果將爲0或1.由於multimap也存在以及相同的界面,因此存在的安全方面更好地與!= 0進行比較。
爲你的榜樣,這是
return (cars.count(name)>0);
我看到的好處是 1.短代碼, 2.無論從任何的優化庫可以在內部應用,使用其代表性的細節好處。
#define itertype(v) typeof((v).begin())
itertype(cars) it = cars.find(name);
return it != cars.end();
爲什麼不使用'auto'而不是這個宏呢? 'auto it = cars.find(name);' – 2017-06-04 18:15:55
歡迎來到SO。這個答案實際上並沒有添加任何新的東西,這些東西在(現在很多的)現有答案中都沒有涉及。考慮刪除你的答案,也許看起來反應回答尚未接受答案的問題。 – 2017-06-04 21:46:57
既然你不會改變'cars',最好是得到'const_iterator'。 – kennytm 2010-05-06 14:42:23
好點。編輯... – Tom 2010-05-06 14:43:02
但是,如果'cars'不是const,'cars.find(name)'將返回一個'iterator',它必須轉換爲'const_iterator','cars.end()'將返回一個'iterator',然後將其與'it'進行比較時轉換爲'const_iterator'。爲什麼要對抗它;爲什麼不使用'iterator'? – 2010-05-06 17:24:00