如果元素是在C++std::map中设置的

If element is set in C++ std::map?

本文关键字:map 设置 C++std 元素 如果      更新时间:2023-10-16

如何确定std::map存储中的元素是否已设置?示例:

#include <map>
#include <string>
using namespace std;
map<string, FOO_class> storage;
storage["foo_el"] = FOO_class();

有类似if (storage.isset("foo_el"))的东西吗?

if (storage.count("foo_el"))

count()返回容器中项目的出现次数,但映射中每个键只能出现一次。因此,如果存在该项,则storage.count("foo_el")为1,否则为0。

尝试storage.find("foo_el") != storage.end();

std::map运算符[]很讨厌:如果不存在,它会创建一个条目,请先使用map::find。

如果您想插入或修改

std::pair<map::iterator, bool> insert = map.insert(map::value_type(a, b));
if( ! insert.second) {
   // Modify insert.first
}

您还可以在插入新的键值对时检查迭代器:

std::map<char,int> mymap;
mymap.insert ( std::pair<char,int>('a',100) );
std::pair<std::map<char,int>::iterator,bool> ret;
ret = mymap.insert ( std::pair<char,int>('a',500) );
if (ret.second==false) {
    std::cout << "element is already existed";
    std::cout << " with a value of " << ret.first->second << 'n';
}