std :: map find()返回错误

std::map find() returning error

本文关键字:返回 错误 find map std      更新时间:2023-10-16

我正在尝试在VS2015中编译以下代码。我的std ::映射的第一个版本是编译,但是秒版本没有编译。请让我知道我在这里做错了什么。

std::map<int, std::string> _p;
typedef std::pair<int, std::string> _q;
_p.insert(_q(0, "Football0"));
_p.insert(_q(1, "Football1"));
std::string str = _p[1];    //OK...compiles and executes, no error, str = "Football1" as expected
std::map<int, DataDictionary> _p1;
typedef std::pair<int, DataDictionary> _q1;
DataDictionary dd1;
dd1.i = 0;
dd1.version = "ver1";
_p1.insert(_q1(0, dd1));
DataDictionary dd2;
dd2.i = 0;
dd2.version = "ver2";
_p1.insert(_q1(1, dd2));
DataDictionary DD = _p1.find[1];    //error C3867: 'std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::find': non-standard syntax; use '&' to create a pointer to member

即使我决定更改我的std ::映射并使用以下内容,我也会遇到相同的错误:

std::map<std::string, DataDictionary> _p1;
DataDictionary DD = _p1.find["1"]; //ERROR

我试图将映射与数据实数结构一起使用,并使用 _p1.find["1"]语法访问元素,因为我假设此方法比将迭代器声明为映射,然后使用find()更快。请帮忙。谢谢,

我试图将映射与数据实数结构一起使用,并使用_p1.find["1"]语法访问元素

不,您正在尝试在成员函数上使用下标运算符:

find("1")会起作用。

find["1"]不应编译。

考虑使用_p1.find("1")_p1["1"]。它们之间的区别在于,查找返回一对在地图中具有位置和布尔标志迭代器(可能已经超过了映射序列的末端),而下标操作员(["1"])返回对现有元素的引用,或者添加一个元素(如果找不到一个元素)并返回对此的引用。

要检查地图是否包含密钥,请改用if(_p1.count("1"))

我认为你的意思是

_p1.find("1");

它将迭代器返回到找到的项目。

使用

std::map<std::string, DataDictionary>::iterator item = _p1.find("1");

在C 11中,您可以做

 auto item = _p1.find("1");