4

私は現在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>]

私は何を間違っていますか?

4

5 に答える 5

4

マップのベクトルを探していないことは確かです。

#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());
}
于 2012-01-24T23:34:33.860 に答える
2

少し話が逸れますが、bimap を使用した魅力的なソリューションを次に示します。これは、両側がキーとして機能するマップです。

#include <iostream>
#include <sstream>
#include <string>
#include <boost/bimap.hpp>
#include <boost/bimap/list_of.hpp>
#include <boost/bimap/set_of.hpp>

int main()
{
    boost::bimap<boost::bimaps::set_of<std::string>, boost::bimaps::list_of<int>> m;

    for (std::string line; std::getline(std::cin, line); )
    {
        ++m.left[line];
    }

    auto & bml = m.left;
    auto & bmr = m.right;

    bmr.sort();

    for (auto const & p : bml) { std::cout << p.first << " => " << p.second << "\n"; }
    for (auto const & p : bmr) { std::cout << p.first << " => " << p.second << "\n"; }
}
于 2012-01-25T00:02:09.857 に答える
1

マップの要素をベクトルに入れたいとします。マップは、他のマップではなくペアで作成されます。したがって、ベクトルはペアのベクトルである必要があります。

とはいえ、最初にベクトルが必要な理由は、マップ内の値でソートするためのようです。map< int, string >それでは、代わりにマップを作成してみませんか? これにより、 ints によって昇順でソートされます。マップ内の要素は、特定の厳密な弱い順序付け基準に従って、キー値の低いものから高いものへとソートされます。

于 2012-01-24T23:39:10.033 に答える
0

astd::map<std::string, int>::const_iteratorを逆参照すると、std::pair<std:string, int>ではなくが得られるstd::map<std::string, int>ため、次の代わりに:

vector<map<string, int> > vec_counters;

あなたはこれを求めている:

vector<std::pair<string, int> > vec_counters;
于 2012-01-24T23:32:24.007 に答える