使用运算符 [ ] 将字符串放入映射中

put string into a map using operator [ ]

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

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;
    }
}

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

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
}

当我 运行 这段代码时,它给了我一个错误:'string'

没有可行的转换

这很简单:

void user::add(int id, string name) 
{
    map[id] = name;
}
    &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,它会抛出异常。

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

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

都有效。您也可以使用指针,但这会带来风险。如果更改地图,您的指针可能会无效。