c++ - boost::unordered_map 中的运算符 []

标签 c++ boost operator-keyword lookup unordered-map

所以,我正在阅读以下网址的 boost::unordered_map 文档:

http://www.boost.org/doc/libs/1_52_0/doc/html/boost/unordered_map.html#id1395195-bb

它说operator[]的效果和返回是

效果: 如果容器尚未包含键等于 k ​​的元素,则插入值 std::pair(k,mapped_type())

返回: 对 x.second 的引用,其中 x 是容器中已有的元素,或者是新插入的元素,其键等于 k

当我运行以下代码时,它显示指向 map [“xyz”]的指针为0。我缺少什么?我看到很多人使用 find(key_value) 但不确定它是如何工作的。

#import <iostream>
#import <boost/unordered_map.hpp>

class myClass
{
public:
    myClass():_i(-1){};
    myClass(int i):_i(i){};
    int _i;
};

int main()
{
    boost::unordered_map<std::string,myClass*> map;
    map["abc"] = new myClass(1);
    std::cout << map["abc"] << std::endl;
    std::cout << map["xyz"] << std::endl;
    return 0;
}

最佳答案

将我的答案从帖子中移至 Yakk 建议的答案。

所以,我解决了自己的问题,并发现其他人可能会从我的经验中受益或提出一些评论,所以我仍在发帖。

我认为发生的事情是它在我的 map 中创建了一个新元素,只是 rhs 是一个 myClass*。我将其重写为

class myClass
{
public:
    myClass():_i(-1){};
    myClass(int i):_i(i){};
    int _i;

    friend std::ostream& operator<< (std::ostream& stream, const myClass& myClass){return stream << "[" << myClass._i << "]";}
};

int main()
{
    boost::unordered_map<std::string,myClass> map;
    map["abc"] = myClass(1);
    std::cout << map["abc"] << std::endl;
    std::cout << map["xyz"] << std::endl;
    return 0;
}

这是我的输出:

$ g++ test.cpp && ./a.out 
[1]
[-1]

希望这可以帮助有需要的人。

关于c++ - boost::unordered_map 中的运算符 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13618702/

相关文章:

c++ - 如何 fread 成类内的 vector ?

c++ - 如何通过串行端口发送请求从目录中检索数据?

c++ - 如何让 CLion 插入生成的代码....在 .cpp 文件中

java - 运算符和方法有什么区别?

Java运算符混淆

c++ - 重载括号运算符有什么作用?

c++ - std::make_pair 与 c++ 11

c++ - boost::asio,线程和同步

c++ - 如何找到像参数一样传递的一些数字的最大序列?

c++ - |运算符 ,++ 和 I 运算符