c++ - 如何删除 C++ 映射中的键值对?

标签 c++ maps

我正在从事一个需要唯一键和值的项目,因此我决定使用 map 。对于有人可能想要更改键值的情况,一切正常。我不确定为什么,但它会导致碎片错误。我不能这样做吗?

void Journal::set_id(int id){               // journal class
    if(join.count(id)){                     // join is: static map <int,string> join
        cout<<"Journal ID is already being used. Try again."<<endl;
    }
    else {
        join.erase (join.find(id));
        join.insert(pair<int,string>(id,name));
    }
}

最佳答案

你的逻辑有问题。

void Journal::set_id(int id){
    if(join.count(id)){
        cout<<"Journal ID is already being used. Try again."<<endl;
    }
    else {
        // When you hit this block of the code, there is nothing
        // in the map corresponding to 'id'.
        // join.find(id) returns the same iterator as join.end()
        // Calling erase() with that iterator is causing you the
        // problem.

        // Don't call erase. Just insert the new item.
        // join.erase (join.find(id));
        join.insert(pair<int,string>(id,name));
    }
}

关于c++ - 如何删除 C++ 映射中的键值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26134172/

相关文章:

c++ - 如何将 std::string 转换为 QString 保留值,反之亦然?

ruby-on-rails - 如何从 rails 中的谷歌地图中选择坐标?

java - QuickHull 算法的复杂性?

c++ - 如何重播我的主要功能? (阅读描述,很难写标题)

javascript - openlayers 3 中带有标签或文本的图标,偏移量

javascript - 谷歌地图 Json 转 GPX

r - 将经纬度坐标转换为R中的国家名称

d3.js - D3js : Automatic labels placement to avoid overlaps?(力斥力)

c++ - 可变大小的对象初始化

python - pybind11 - ImportError : undefined symbol: _Py_ZeroStruct