小编wea*_*007的帖子

如何通过迭代器将 map<string, int> 推回矢量 <map<string, int>> ?

我目前正在学习《Accelerated C++》(Koening/Moo)一书,但其中一个练习遇到了问题。任务是编写一个程序,该程序将一些单词序列作为输入,然后将其存储在map<string, int>. 字符串是输入的单词,关联的int是每个单词出现的次数。然后你必须按照单词出现的次数对它们进行排序;也就是说,通过值而不是键。您无法按值对映射进行排序,因此我尝试将元素复制到向量中,我打算使用谓词对其进行排序。不幸的是,我得到的只是一个充满 g++ 错误的屏幕。它们似乎源于同一个地方 - 将我的地图元素放入我的向量中,我尝试这样做:

\n\n
int main()\n{\n    map<string, int> counters;\n\n    cout << "Enter some words followed by end-of-file (ctrl-d): ";\n    string word;\n    while (cin >> word)\n       ++counters[word];\n\n    // Maps cannot be sorted by values, so pass the elements of counters to a vector.\n    vector<map<string, int> > vec_counters;\n\n    map<string, int>::const_iterator it = counters.begin();\n    while (it != counters.end()) {\n       vec_counters.push_back(*it);\n       ++it;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这显然只是第一部分,但我什至无法编译它。我收到以下错误:

\n\n
\n

32:31: 错误: 没有匹配的函数用于调用 std::vector, int> >::push_back(const …

c++ dictionary iterator vector push-back

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

c++ ×1

dictionary ×1

iterator ×1

push-back ×1

vector ×1