C ++:Unordered_map.emplace(char,int)未设置预期值

时间:2017-10-14 03:32:36

标签: c++ hash

我尝试在C ++中使用unordered_maps来创建哈希表。 我尝试为char键写入值1,看到0写入。 不确定我错过了什么,非常感谢任何帮助!

#include <iostream>
#include <unordered_map>
#include <string>

using namespace std;

class Solution {
public:
       void lengthOfLongestSubstring(string s)
       {
            unordered_map< char, int > hash;
            int i = 0;
            int j = 0;
            while(i < (int)s.length() && j < (int)s.length())
            {
                 if(hash[s[j]])
                    {
                        hash[s[i]] = 0;
                        cout<<"hash removed"<<hash[s[i]]<<"to char"<<s[i]<<endl;
                        i++;
                    }
                 else
                    {
                        hash.emplace(s[j],1);
                        cout<<"hash added"<<hash[s[j]]<<"to char"<<s[j]<<endl;
                        j++;
                    }
            }
            cout<<"iterating through hash"<<endl;
            int max = 0;
            for(auto &itr : hash)
                {
                    cout<<"hash"<<itr.first<<itr.second<<endl;
                    max++;
                }
           cout<<"max"<<max<<endl;
           return;
         }
      };

      int main(int argc, char **argv)
        {
            Solution s;
            s.lengthOfLongestSubstring("abcade");
            return 0;
        }

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

输出我得到:

hash added0to chara

hash added0to charb

hash added0to charc

hash added0to chara

hash added0to chard

hash added0to chare

迭代哈希

hashe0

hasha0

hashb0

hashc0

hashd0

MAX5

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

我希望哈希添加1到chara,但是看到0代替!

1 个答案:

答案 0 :(得分:0)

因为@Igor Tandetnik指出if(hash [s [i]]访问是创建一个哈希条目,因为emplace()只创建一个条目,如果它不存在,那么该值永远不会更新。