Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`auto-increment` std::map<string, int> :)

Ok, the problem is pretty straightforward - I am reading words from the input stream, the words may repeat. I need to populate a map so that all the words get indices from 0 to n-1. Here is my code:

map<string, int> mp;
string s;
int n = 0;
while(cin >> s)
{
   if(mp.find(s) == mp.end())
   {
      mp.insert(make_pair(s, n++));
   }
}

Is this the best way to achieve what I want to achieve or are there more elegant, more STL-ish solutions? Thanks in advance

like image 813
Armen Tsirunyan Avatar asked Apr 18 '26 02:04

Armen Tsirunyan


1 Answers

You don't need to check whether there is an element at that key before you insert because insert doesn't change the mapped value if the key already exists. You don't need to keep track of the count separately; you can just call size() to get the next value:

while (std::cin >> s)
{
    mp.insert(std::make_pair(s, mp.size()));
}
like image 123
James McNellis Avatar answered Apr 19 '26 14:04

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!