简体   繁体   English

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

[英]`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. 我需要填充一个地图,以便所有单词都得到从0到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? 这是实现我想要达到的目标的最佳方法,还是有更优雅,更类似于STL的解决方案? 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. 在插入之前,您不需要检查该键上是否有任何元素,因为如果键已经存在,则insert不会更改映射值。 You don't need to keep track of the count separately; 您无需单独跟踪计数; you can just call size() to get the next value: 您可以只调用size()以获得下一个值:

while (std::cin >> s)
{
    mp.insert(std::make_pair(s, mp.size()));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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