从具有 3 个元素的无序映射中删除值
Delete value from unordered-map with 3 elements
这是我正在使用的无序地图的 MWE。根据我的理解here,public成员函数"erase"用于从无序映射中删除元素。
#include <iostream>
#include <string>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main() {
std::unordered_map<int, std::pair<int, int> > m;
m.insert({3, std::make_pair(1,1)});
m.insert({4, std::make_pair(5,1)});
cout << m[4].first << endl;
m.erase(4);
cout << m[4].first << endl;
}
但是,我从这个例子中看到的是:
5
0
我只期待 5
然后抛出密钥不存在的错误。
我错过了什么?
正如documentation中所指出的,如果一个值在unordered_map
中不存在,operator[]
将引入一个具有相应键的新元素。在第二个查询中返回的是 default-constructed 对,由 operator[]
.
构造
正如@you 在他的评论中指出的那样,您可以改用 at()
,其中包含 "range" 检查并在密钥现在位于 [= 中时抛出 std::out_of_range
异常10=].
如果你想避免异常,你可以先检查是否m.find(4)==m.end()
,这表明键4不在地图中,正如@YSC在他的评论中所指出的。
这是我正在使用的无序地图的 MWE。根据我的理解here,public成员函数"erase"用于从无序映射中删除元素。
#include <iostream>
#include <string>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main() {
std::unordered_map<int, std::pair<int, int> > m;
m.insert({3, std::make_pair(1,1)});
m.insert({4, std::make_pair(5,1)});
cout << m[4].first << endl;
m.erase(4);
cout << m[4].first << endl;
}
但是,我从这个例子中看到的是:
5
0
我只期待 5
然后抛出密钥不存在的错误。
我错过了什么?
正如documentation中所指出的,如果一个值在unordered_map
中不存在,operator[]
将引入一个具有相应键的新元素。在第二个查询中返回的是 default-constructed 对,由 operator[]
.
正如@you 在他的评论中指出的那样,您可以改用 at()
,其中包含 "range" 检查并在密钥现在位于 [= 中时抛出 std::out_of_range
异常10=].
如果你想避免异常,你可以先检查是否m.find(4)==m.end()
,这表明键4不在地图中,正如@YSC在他的评论中所指出的。