确定STL映射是否包含给定键的值的最佳方法是什么?
#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;
}
Run Code Online (Sandbox Code Playgroud)
在调试器中检查它,它看起来就像iter垃圾数据.
如果我取消注释这一行:
Bar b2 = m[2]
Run Code Online (Sandbox Code Playgroud)
调试器显示的b2是{i = 0}.(我猜这意味着使用未定义的索引会返回一个包含所有空/未初始化值的结构?)
这些方法都不是很好.我真正喜欢的是这样的界面:
bool getValue(int key, Bar& out)
{
if (map contains value for key)
{
out = map[key];
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
沿着这些线存在什么?
小智 305
只要地图不是多图,最优雅的方法之一就是使用count方法
if (m.count(key))
// key exists
Run Code Online (Sandbox Code Playgroud)
如果元素确实存在于地图中,则计数将为1.
Ala*_*lan 253
沿着这些线存在什么?
不可以.使用stl map类,您可以使用::find()搜索地图,并将返回的迭代器与之比较std::map::end()
所以
map<int,Bar>::iterator it = m.find('2');
Bar b3;
if(it != m.end())
{
//element found;
b3 = it->second;
}
Run Code Online (Sandbox Code Playgroud)
显然你可以getValue()根据自己的需要编写自己的例程(也是在C++中,没有理由使用out),但是我怀疑一旦你掌握了使用它就std::map::find()不会浪费你的时间.
你的代码也有点错误:
m.find('2');将在地图中搜索关键值'2'.IIRC C++编译器将隐式地将'2'转换为int,这导致'2'的ASCII代码的数值,这不是你想要的.
由于您在此示例中的键类型是int要搜索,如下所示:m.find(2);
sti*_*472 50
它已经存在,只有查找不是那种确切的语法.
if (m.find(2) == m.end() )
{
// key 2 doesn't exist
}
Run Code Online (Sandbox Code Playgroud)
如果要访问该值(如果存在),您可以执行以下操作:
map<int, Bar>::iterator iter = m.find(2);
if (iter != m.end() )
{
// key 2 exists, do something with iter->second (the value)
}
Run Code Online (Sandbox Code Playgroud)
使用C++ 0x和auto,语法更简单:
auto iter = m.find(2);
if (iter != m.end() )
{
// key 2 exists, do something with iter->second (the value)
}
Run Code Online (Sandbox Code Playgroud)
我建议你习惯它,而不是试图想出一个新的机制来简化它.您可以减少一些代码,但要考虑这样做的成本.现在,您已经介绍了一个熟悉C++的人无法识别的新功能.
如果你想要实现这一点,尽管有这些警告,那么:
template <class Key, class Value, class Comparator, class Alloc>
bool getValue(const std::map<Key, Value, Comparator, Alloc>& my_map, int key, Value& out)
{
typename std::map<Key, Value, Comparator, Alloc>::const_iterator it = my_map.find(key);
if (it != my_map.end() )
{
out = it->second;
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
keb*_*ebs 24
我只是注意到使用C++ 20,我们会有
bool std::map::contains( const Key& key ) const;
Run Code Online (Sandbox Code Playgroud)
如果map持有带键的元素,那将返回true key.
简单总结一下其他一些答案:
如果您还没有使用 C++ 20,您可以编写自己的mapContainsKey函数:
bool mapContainsKey(std::map<int, int>& map, int key)
{
if (map.find(key) == map.end()) return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
如果您想避免mapvsunordered_map以及不同的键和值类型的许多重载,您可以将其设为template函数。
如果你正在使用C++ 20或以后,会有一个内置contains函数:
std::map<int, int> myMap;
// do stuff with myMap here
int key = 123;
if (myMap.contains(key))
{
// stuff here
}
Run Code Online (Sandbox Code Playgroud)
find检查against的返回值end。
map<int, Bar>::iterator it = m.find('2');
if ( m.end() != it ) {
// contains
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
319320 次 |
| 最近记录: |