我有以下问题-我想计数每个字在一个文件中的出现。我使用的是一个map<string,Count>,所以键是表示单词的string对象,所查找的值是保持字符串计数的对象,以便:
class Count {
int i;
public:
Count() : i(0) {}
void operator++(int) { i++; } // Post-increment
int& val() { return i; }
};问题是我想使用insert()而不是operator[]。这是密码。
typedef map<string, Count> WordMap;
typedef WordMap::iterator WMIter;
int main( ) {
ifstream in("D://C++ projects//ReadF.txt");
WordMap wordmap;
string word;
WMIter it;
while (in >> word){
// wordmap[word]++; // not that way
if((it= wordmap.find(word)) != wordmap.end()){ //if the word already exists
wordmap.insert(make_pair(word, (*it).second++); // how do I increment the value ?
}else{
...
}
for (WMIter w = wordmap.begin();
w != wordmap.end(); w++)
cout << (*w).first << ": "
<< (*w).second.val() << endl;
}发布于 2017-10-09 12:18:58
问题是我想使用
insert()而不是operator[]
...why?std::map::insert不能更改现有值。operator[]是这方面的最佳工作。
如果您真的想使用insert (请不要使用),首先需要erase现有的值,如果是这样的话:
if((it= wordmap.find(word)) != wordmap.end())
{
const auto curr = it->second; // current number of occurrences
wordmap.erase(word);
wordmap.insert(make_pair(word, curr + 1));
}发布于 2020-06-13 12:08:21
您是否可以重构,以便不使用“查找”,而只是尝试插入?
插入总是返回一个pair<iter*, bool>。如果找到键,则bool为0,iter*指向现有的对。因此,我们可以获取指向对的指针并增加值:
// On successful insertion, we get a count of 1 for that word:
auto result_pair = wordmap.insert( { word, 1 } );
// Increment the count if the word is already there:
if (!result_pair.second)
result_pair.first->second++;这是我第一次发帖。我正在学习C++,并欢迎对我的想法的反馈。
https://stackoverflow.com/questions/46646225
复制相似问题