我想编写一个程序,它将字符串列表作为输入,并创建带有字符串名称和位置的哈希表。矢量词{“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