确定地图是否包含键的值?
确定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;
}
显然你可以编写自己的 getValue() / code>例程,如果你想(也在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,这样可以得到ASCII码为2的数值,这不是您想要的。
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.
因为这个例子中的keytype是 int
,你想这样搜索: m.find(2);
Since your keytype in this example is int
you want to search like this: m.find(2);