我想編寫一個程序,它將字符串列表作爲輸入,並創建帶有字符串名稱和位置的哈希表。矢量詞{「first」,「second」,「third」,「fourth」,「second」};以及其他數據。C++ unordered_map插入到向量
輸出:
第1
第二2,5
第三3
提出4
我面臨兩個問題,請找到它們在下面的代碼註釋。
請告訴我我做錯了什麼?
int main()
{
vector<string> words {"first", "second", "third", "forth", "second"};
unordered_map<string, vector<int>> hash_table;
unordered_map<string, vector<int>>::const_iterator hash_it;
int loc = 1;
for(auto n = words.begin(); n != words.end(); ++n){
hash_it = hash_table.find(*n);
if(hash_it == hash_table.end())
hash_table.insert(make_pair(*n, vector<int> (loc)));
else
//hash_it->second.push_back(loc); //Problem 1 - this statement gives error
++loc;
}
for(auto& n:hash_table){
cout<<"Word - "<<n.first<<" Loc -";
vector<int> tmp1 = n.second;
for(auto j = tmp1.begin(); j != tmp1.end(); ++j)
cout<<" "<<*j;
cout<<endl;
}
}
問題2 - 位置的值是節目0
輸出 -
字 - 所述祿 - 0
字 - 第三祿 - 0
字 - 第二祿 - 0
字 - 第一祿 - 0
歡迎堆棧溢出。請花些時間閱讀[The Tour](http:// stackoverflow。com/tour),並參考[幫助中心](http://stackoverflow.com/help/asking)中的內容以及您可以在此處詢問的內容。 –
編譯失敗到底是什麼錯誤? –
@ABusyProgrammer錯誤是 - 在函數 '詮釋主()': 23點42:錯誤:使 '常量性病::矢量' 作爲 '這個' 的「無效參數的std ::矢量<_Tp, _Alloc> ::的push_back(常量VALUE_TYPE& )[with _Tp = int; _Alloc = std :: allocator ; std :: vector <_Tp, _Alloc> :: value_type = int]'丟棄限定符[-fpermissive] –
cplusplusnoob