我目前正在学习Accelerated C++ (Koening/Moo) 这本书,但其中一个练习有问题。任务是编写一个程序,将一些单词序列作为输入,然后将其存储在map<string, int>
. 字符串是输入的单词,相关int
的是每个单词出现的次数。然后,您必须按单词出现的次数对单词进行排序;也就是说,按值而不是键。您不能按值对地图进行排序,因此我尝试将元素复制到向量中,而我打算使用谓词对其进行排序。不幸的是,我得到的只是一个充满 g++ 错误的屏幕。它们似乎来自同一个地方 - 将我的地图元素放入我的向量中,我尝试这样做:
int main()
{
map<string, int> counters;
cout << "Enter some words followed by end-of-file (ctrl-d): ";
string word;
while (cin >> word)
++counters[word];
// Maps cannot be sorted by values, so pass the elements of counters to a vector.
vector<map<string, int> > vec_counters;
map<string, int>::const_iterator it = counters.begin();
while (it != counters.end()) {
vec_counters.push_back(*it);
++it;
}
}
这显然只是第一部分,但我什至无法编译。我收到以下错误:
32:31: 错误: 没有匹配函数调用 std::vector, int> >::push_back(const std::pair, int>&)' /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::allocator, int> >, value_type = std::map, 整数>]
我究竟做错了什么?