【发布时间】:2018-01-11 03:54:25
【问题描述】:
在 C++ 中有模拟 IDictionary.ContainsKey (TKey) 或 List.Contains (T) 来自 C# 吗?
例如,我有一个元素数组,需要知道这个数组是否有一些值? 什么是最佳方式或最佳实践 - 每个元素都没有“foreach”! 例如,如果它来自 std 库,那就太好了。
UPD 1:在标准库中有很多容器,但我想找到一个最好的方法——更快、代码少、复杂度低等等......
如果继续this logic,则更好的设计是std::unordered_set
#include <unordered_set>
std::unordered_set<std::string> NamesOfValues = {
"one",
"two",
"Date",
"Time"
};
// and now check is value exists in set
if(NamesOfValues.count(value))
{
// value exists
}
【问题讨论】:
-
可以看看 std::map (特别是 find() 函数):cplusplus.com/reference/map/map/find
-
可能,我看了一下 - 但可能有更好的设计 - 例如 std::map::count 看起来更好......
-
@underscore_d- 我知道例如 std lib 有许多容器用于存储 map、set 等值 - 我询问更好的设计和最佳实践!
-
也许你能找到答案here
标签: c++ c++11 stl containers