我正在从事一个需要唯一键和值的项目,因此我决定使用 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/