在抛出 'std::out_of_range' 的实例后调用终止?
terminate called after throwing an instance of 'std::out_of_range'?
我正在尝试查看 map
中是否存在特定键,如果存在,那么我想将其值增加 1。但是当 运行 程序出现错误时
terminate called after throwing an instance of 'std::out_of_range'
what(): map::at
为什么会这样out_of_range
有人可以帮忙吗?
b is a map in this function.
itr is an iterator for accessing its elements
for(int i=0;i<n;i++)
{
ct=0;
cin>>a[i];
for(itr=b.begin();itr!=b.end();itr++)
{
if(itr->first==a[i])
ct++;
else
continue;
}
if(!ct)
{
b.at(a[i])++;
}
else
{
b.insert(pair <int,int>(a[i],1));
}
}
}
你只需 3-4 行就可以写出全部内容:
for (int i = 0; i < n; ++i) {
cin >> a[i];
++b[a[i]];
}
如果 a[i]
在映射 b
中不存在,则 subscript operator 将自动插入 {a[i], 0}
。然后递增它使其等同于您尝试插入一对 {a[i], 1}
.
的代码
你的方法有什么问题:
你在做b.at(a[i])++
之前使用的条件是错误的。应该是 if (ct)
而不是 if (!ct)
.
[改进]
您本可以在发现 itr->first == a[i]
为真时添加 break
。但它的复杂性仍然是时间 O(n)
。这违背了使用 std::map
而不是 std::vector<std::pair<int, int>>
的初衷。如果您使用 std::map::find
instead. (More methods here,则可以以对数时间复杂度执行该操作。)
我正在尝试查看 map
中是否存在特定键,如果存在,那么我想将其值增加 1。但是当 运行 程序出现错误时
terminate called after throwing an instance of 'std::out_of_range' what(): map::at
为什么会这样out_of_range
有人可以帮忙吗?
b is a map in this function. itr is an iterator for accessing its elements
for(int i=0;i<n;i++)
{
ct=0;
cin>>a[i];
for(itr=b.begin();itr!=b.end();itr++)
{
if(itr->first==a[i])
ct++;
else
continue;
}
if(!ct)
{
b.at(a[i])++;
}
else
{
b.insert(pair <int,int>(a[i],1));
}
}
}
你只需 3-4 行就可以写出全部内容:
for (int i = 0; i < n; ++i) {
cin >> a[i];
++b[a[i]];
}
如果 a[i]
在映射 b
中不存在,则 subscript operator 将自动插入 {a[i], 0}
。然后递增它使其等同于您尝试插入一对 {a[i], 1}
.
你的方法有什么问题:
你在做b.at(a[i])++
之前使用的条件是错误的。应该是 if (ct)
而不是 if (!ct)
.
[改进]
您本可以在发现 itr->first == a[i]
为真时添加 break
。但它的复杂性仍然是时间 O(n)
。这违背了使用 std::map
而不是 std::vector<std::pair<int, int>>
的初衷。如果您使用 std::map::find
instead. (More methods here,则可以以对数时间复杂度执行该操作。)