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

wea*_*007 5 c++ dictionary iterator vector push-back

我目前正在学习《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 std::pair, int>&)\xe2\x80\x99\n /usr/include/c++/4.5 /bits/stl_vector.h:741:7:注意:候选者是:void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::map, int>, _Alloc = std::分配器,int>>,value_type = std::map,int>]

\n
\n\n

我究竟做错了什么?

\n

seh*_*ehe 5

我很确定您不是在寻找地图矢量:

#include <map>
#include <vector>
#include <string>
#include <iostream>

using namespace std;
int main()
{
    map<string, int> counters;

    cout << "Enter some words followed by end-of-file (ctrl-d): ";
    string word;
    while (cin >> word)
       ++counters[word];

    vector<std::pair<string, int> > vec(counters.begin(), counters.end());
}
Run Code Online (Sandbox Code Playgroud)