简体   繁体   中英

`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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM