【问题标题】:incrementing the value in map using insert c++使用插入C++增加地图中的值
【发布时间】:2017-10-09 12:15:19
【问题描述】:

我有以下问题 - 我想计算文件中每个单词的出现次数。我使用的是map<string,Count>,所以键是代表单词的字符串对象,而要查找的值是保持字符串计数的对象,以便:

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

【问题讨论】:

  • 使用std::map&lt;string, std::size_t&gt;wordmap[word]++; 有什么问题?
  • @NathanOliver 我正在做一些练习,我必须用insert() 来做。无论如何,下面的答案对我来说很清楚。
  • 如果值已经存在,insert 不会插入任何东西。
  • 如果你想使用insert是问题所在,那么解决方案是:改变主意,不要使用insert:P

标签: c++ dictionary insert


【解决方案1】:

您能否重构以便不使用 find 而只是尝试插入?

插入总是返回pair&lt;iter*, bool&gt;。如果找到密钥,则布尔值为 0,并且 iter* 指向现有对。所以我们可以将指针指向pair并增加值:

// 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++,欢迎对我的想法提出反馈。

【讨论】:

    【解决方案2】:

    问题是我想使用insert() 而不是operator[]

    ...为什么? 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)); 
    }
    

    【讨论】:

    • 使用 C++17 会更好看:if (auto it = wordmap.find(word); it != wordmap.end()) { ... }
    猜你喜欢
    • 1970-01-01
    • 2012-03-13
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 2018-06-28
    • 1970-01-01
    相关资源
    最近更新 更多