开发者

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

开发者 https://www.devze.com 2023-01-23 23:03 出处:网络
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.

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 bes开发者_Go百科t 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()));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消