私は現在Accelerated C++ (Koening/Moo) という本を勉強していますが、演習の 1 つに問題があります。タスクは、入力として一連の単語を受け取り、それを に格納するプログラムを作成すること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, int>]
私は何を間違っていますか?