使用哪种方法检查std :: map中是否存在数组键?

New*_*bie 1 c++

我在某些情况下使用以下代码:

#define array_key_exists(find_key, arr) (arr.find(find_key) != arr.end())
Run Code Online (Sandbox Code Playgroud)

但我也只使用这种方法:

if(SomeMap["something"]){
    // key exists
}
Run Code Online (Sandbox Code Playgroud)

我正在使用String to int map.

它们都快吗......?或者假设我没有在地图值中使用零值,第二种情况是否有可能出现错误?到目前为止,第二种情况似乎工作正常.

GMa*_*ckG 12

将始终输入第二个if语句,因为如果该键不存在,则将创建该语句.(之后,后续调用将只返回现有元素.)

如果要查找值并使用它(如果存在),通常执行以下操作:

std::map<T>::iterator iter = theMap.find(theKey);
if (iter != theMap.end())
{
    // use iter
}
else
{
    // value doesn't exist
}
Run Code Online (Sandbox Code Playgroud)

如果您只是想知道它是否在那里,而不使用它,请执行:

if (theMap.count(theKey)) // in map, count will return either 0 or 1
{
    // it exists
}
else
{
    // it doesn't exist
}
Run Code Online (Sandbox Code Playgroud)

至少,不要使用宏!在C++中没有理由:

template <typename Map, typename Key>
bool contains(const Map& pMap, const Key& pKey)
{
    return pMap.find(pKey) != pMap.end();
}
Run Code Online (Sandbox Code Playgroud)

但是没有用,只需使用count.