Reputation: 67
I am trying to see if a particular key exists in map
and if so then I want to increase its value by 1. But while running the program I am getting the error
terminate called after throwing an instance of 'std::out_of_range' what(): map::at
Why is it going out_of_range
can someone help?
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));
}
}
}
Upvotes: 0
Views: 1854
Reputation: 13014
You can write this whole thing in just 3-4 lines :
for (int i = 0; i < n; ++i) {
cin >> a[i];
++b[a[i]];
}
The subscript operator will automatically insert {a[i], 0}
, if a[i]
is not there as a key in map b
. Then incrementing it makes it equivalent to your code where you try to insert a pair {a[i], 1}
.
What was wrong with your approach :
The condition that you used before doing b.at(a[i])++
is wrong. It should have been if (ct)
not if (!ct)
.
[Improvements]
You could have put a break
on finding itr->first == a[i]
to be true. But still it's complexity was time O(n)
. That defies the very purpose of using std::map
instead of std::vector<std::pair<int, int>>
. You can perform that operation in logarithmic time complexity if you used std::map::find
instead. (More methods here.)
Upvotes: 2