使用operator []将字符串放入地图

时间:2015-10-06 02:58:12

标签: c++ string dictionary operators add

我有map<int,string>为每个name添加id。 我有办法做到这一点。

void User::add(int id, string name) {
    map<int, string>::iterator it = map.find(id);
    if (it == map.end()) {
        map.insert(pair<int, string>(id, name));
    } else {
        it->second = name;
    }
}

它工作得非常好。但我想学习如何使用operator []将字符串添加到地图中。以下是我的代码:

void user::add(int id, string name) {
    &auto findUser = map[id];//check if an user exists
    findUser.push_back(string()); // add a new string object
    findUser.push_back(name); // put string into the map
}

当我运行此代码时,它给了我一个错误:没有可靠的转换来自&#39;字符串&#39;

2 个答案:

答案 0 :(得分:4)

    &auto findUser = map[id];//check if an user exists

首先,我假设领先的&是一个拼写错误,因为它在宣言的那一边毫无意义。

map[id]将找到映射到id的字符串。如果没有这样的字符串the map will invent one, stuff it into the map, and return a reference to the brand new string。您将始终返回一个字符串引用。

因为您将返回一个字符串引用,auto findUser将是一个字符串引用。其余的代码试图将字符串推入字符串,你已经看到了结果。这是auto的危险之一。尽管我喜欢它,它隐藏了OP的实际数据类型,并使错误消息更加神秘。

您无法使用[]有效地检查地图中的状态。当然,你可以测试空字符串,但现在你有一个空字符串使你的地图混乱。很快,你在地图上有很多空字符串。不是一个好的解决方案。

map.find与测试存在性一样好。下一个最好的可能是map.at(id),因为如果找不到id,它将抛出异常。

从好的方面来说,因为[]返回对映射类型的引用,所以它可以像使用数组一样使用。

name = map[id];
map[id] = name;

都有效。你也可以拿一个指针,但这带来了风险。如果地图被更改,您的指针可能无效。

答案 1 :(得分:2)

这很简单:

void user::add(int id, string name) 
{
    map[id] = name;
}
相关问题