确定map是否包含键的值? [英] Determine if map contains a value for a key?

查看:181
本文介绍了确定map是否包含键的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定STL地图是否包含给定键的值的最佳方法是什么?

What is the best way to determine if a STL map contains a value for a given key?

#include <map>

using namespace std;

struct Bar
{
    int i;
};

int main()
{
    map<int, Bar> m;
    Bar b = {0};
    Bar b1 = {1};

    m[0] = b;
    m[1] = b1;

    //Bar b2 = m[2];
    map<int, Bar>::iterator iter = m.find(2);
    Bar b3 = iter->second;

}

在调试器中检查它,看起来像 iter 只是垃圾数据。

Examining this in a debugger, it looks like iter is just garbage data.

如果我取消注释此行:

Bar b2 = m[2]

调试器显示 b2 {i = 0} 。 (我猜这意味着使用未定义的索引将返回一个结构与所有空/未初始化的值?)

The debugger shows that b2 is {i = 0}. (I'm guessing it means that using an undefined index will return a struct with all empty/uninitialized values?)

这些方法都不是那么伟大。我真的很喜欢这样的界面:

Neither of these methods is so great. What I'd really like is an interface like this:

bool getValue(int key, Bar& out)
{
    if (map contains value for key)
    {
        out = map[key];
        return true;
    }
    return false;
}

这些行是否存在?

推荐答案


这些行是否存在?

Does something along these lines exist?

否。使用stl地图类,您可以使用 :: find() 搜索地图,并将返回的迭代器与 std :: map :: end()

No. With the stl map class, you use ::find() to search the map, and compare the returned iterator to std::map::end()

so

map<int,Bar>::iterator it = m.find('2');
Bar b3;
if(it != m.end())
{
   //element found;
   b3 = it->second;
}


$ b 例程如果你想(也在C ++,没有理由使用 out ),但我怀疑,一旦你得到使用 std :: map :: find()你不会浪费你的时间。

Obviously you can write your own getValue() routine if you want (also in C++, there is no reason to use out), but I would suspect that once you get the hang of using std::map::find() you won't want to waste your time.

您的代码有点错误:

m.find('2'); 映射为'2'的键值。 IIRC C ++编译器会隐式地将'2'转换为一个int,这将产生'2'的ASCII码的数值,这不是你想要的。

m.find('2'); will search the map for a keyvalue that is '2'. IIRC the C++ compiler will implicitly convert '2' to an int, which results in the numeric value for the ASCII code for '2' which is not what you want.

因为你的键类型在这个例子中是 int 你想这样搜索: m.find(2);

Since your keytype in this example is int you want to search like this: m.find(2);

这篇关于确定map是否包含键的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆