【问题标题】:put string into a map using operator [ ]使用运算符 [ ] 将字符串放入地图
【发布时间】:2016-01-02 20:11:53
【问题描述】:

我有一个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'没有可行的转换

【问题讨论】:

  • 为了便于阅读,建议不要使用名为 map 的地图。

标签: c++ string dictionary operators add


【解决方案1】:
    &auto findUser = map[id];//check if an user exists

首先,我假设前导 &amp; 是一个错字,因为它在声明的那一侧没有意义。

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;

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

【讨论】:

    【解决方案2】:

    这很简单:

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

    【讨论】:

    • 请注意,这个是盲人。它将替换 id 处的名称,OP 在最初的剪辑中竭尽全力避免。
    • 好吧。他正在替换原始代码中现有id 的名称。如果他想避免这种情况,将有return 而不是it-&gt;second = name;
    • 没有。在原始代码中,OP 测试 id 的存在,如果不存在则只添加字符串。这是地图operator[] 无法做到的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 2017-06-20
    • 2016-01-26
    相关资源
    最近更新 更多