使用内部结构构建器进行映射

时间:2016-04-16 16:01:44

标签: c++ dictionary struct builder

我有一张内部sruct的地图:

struct Messages {
    unsigned int id;
    string user_name;
    string content;
    time_t timestamp;

    Messages(const string& a_user_name, const string& a_content) :
        user_name(a_user_name), content(a_content), id(++last_id)
    {
        timestamp = time(0);
    }
};

map<unsigned int, Messages> Global_messages;

当我尝试访问元素时:

cout << Global_messages[i].id;

它给我一个关于没有合适的建设者的错误。

1 个答案:

答案 0 :(得分:2)

std::map::operator[]要求该值为默认可构造,而Messages不是这种情况。您必须使用其他界面insert / emplace来填充地图,atfind来检索值