c++ - 如何在 std::map 中插入自定义对象

标签 c++

我正在尝试插入对我的对象的引用,但出现了大量错误。自定义对象需要修改什么才能插入成功?

代码如下:

#include <map>
#include <iostream>
#include <string>

using namespace std;

class A
{
public:
    A()
    {
            cout << "default constructor" << endl;
    }

    A(A & a)
    {
            cout << "copy constructor" << endl;
    }

    A & operator=(A & a)
    {
            cout << "assignment operator" << endl;
            return *this;
    }

    ~A()
    {
            cout << "destructor" << endl;
    }
};

int main()
{
    map<string, A&> m1;
    A a;
    m1["a"] = a;
    return 0;
}

更新:

  1. 可以创建带有引用的 map ,例如 map<string, A&>

  2. 错误是在使用 [] 运算符时。通过进行以下更改,代码可以正常工作

    typedef map<string, A&> mymap;
    
    int main()
    {
       mymap m1;
       A a;
       cout << &a << endl;
       m1.insert(make_pair<string, A&>("a", a));
       mymap::iterator it = m1.find("a");
       A &b = (*it).second;
       cout << &b << endl; // same memory address as a
       return 0;
    }
    

最佳答案

您不能在map 中存储引用。请改用指针。

替换:

map<string, A&> m1;

与:

map<string, A*> m1;

或者更好(感谢 WhozCraig!):

map<string, shared_ptr<A> > m1;

关于c++ - 如何在 std::map 中插入自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15532157/

相关文章:

C++ 堆栈内存仍然有效吗?

c# - 在 C# 中实现与 CTime.GetTime() 方法相同的行为

c++ - 将摩尔斯电码插入二叉树

c++ - 获取数组/vector 末尾地址的未定义行为?

c++ - 现有的标准仿函数/函数来检查是否等于 0?

c++ - 基本 GL 函数 glTranslatef 似乎不起作用

c++ - 如何根据对象是否为右值引用路由到不同的实现?

c++ - 重载运算符试图将另一个重载运算符作为参数

c++ - Google 关于输入/输出参数作为指针的风格指南

c++ - 如何获取卫星资源 DLL 的模块句柄? (C++ Visual Studio )