0

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));
        }
    }

}
Vishnu CS
  • 748
  • 1
  • 10
  • 24
logan007
  • 67
  • 1
  • 10
  • **a** is just an integer array. – logan007 Sep 16 '20 at 06:12
  • see [this page about std::map::at](https://en.cppreference.com/w/cpp/container/map/at), maybe `a[i]` is not in map's keyset, thus result in the `out_of_range` exception. – SHP Sep 16 '20 at 06:13
  • 5
    `if(!ct)` should presumably be `if(ct)`. Note your for loop should probably just be replaced with `std::map::find` – Alan Birtles Sep 16 '20 at 06:14
  • 3
    The whole outer `i` loop body can be replaced by `cin >> a[i]; auto p = b.insert({a[i],0}); p.first++;`. It will be also more efficient. – Daniel Langr Sep 16 '20 at 06:18

1 Answers1

2

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.)

brc-dd
  • 10,788
  • 3
  • 47
  • 67