1

ファイルからチーム名を読み取り、それらをグループに分割するプログラムを作成しています。サイズ 4 の各グループ。

map<int, set<string> > groups

チーム名は国名であると仮定します。すべてのチーム名を担当者に入力した後。グループ 各グループの内容を印刷したいのですが、ここで行き詰まっています。

これが完全な作業コードです。これまでに書いたものです。

#include<iostream>
#include<vector>
#include<ctime>
#include<cstdlib>
#include<algorithm>
#include<map>
#include<set>
using namespace std;
void form_groups(vector<string>);
int main(){
        srand(unsigned(time(NULL)));
        string team_name;
        vector<string> teams;
        while (cin >> team_name)
        {
                teams.push_back(team_name);
        }
        random_shuffle(teams.begin(), teams.end());
        form_groups(teams);
}
void form_groups(vector<string> teams)
{
        map<int, set<string> > groups;
        map<int, set<string> >::iterator it;
        string curr_item;
        int curr_group = 1;
        int count = 0;
        for(int i = 0; i < teams.size(); i++)
        {
                curr_item = teams.at(i);
                count++;
                if(count == 4)
                {
                        curr_group += 1;
                        count = 0;
                }
                groups[curr_group].insert(curr_item);
        }
        cout << curr_group << endl;
        for(it = groups.begin(); it != groups.end(); ++it)
        {
        }
}
4

3 に答える 3

2

あなたのアプローチは問題ありません。を使用すると、指定されたペアに と でアクセスmap<int, set<string> >::iterator itできます。はそれ自体が標準のコンテナであるため、 を使用して要素をトラバースできます。<key,value>it->firstit->secondset<string>set<string>::iterator

map<int, set<string> >::iterator map_it;
set<string>::iterator set_it

for(map_it = groups.begin(); map_it != groups.end(); ++map_it){
    cout << "Group " << it->first << ": ";

    for(set_it = map_it->second.begin(); set_it != map_it->second.end(); ++set_it)
         cout << *set_it << " ";

    cout << endl;
}
于 2012-07-08T09:21:32.120 に答える
1

を反復処理するとstd::map<..>it->firstキーit->secondが得られ、対応する値が得られます。

マップを反復処理するには、次のようなものが必要です。

for(it = groups.begin(); it != groups.end(); ++it)
{
    cout<<"For group: "<<it->first<<": {"; //it->first gives you the key of the map.

    //it->second is the value -- the set. Iterate over it.
    for (set<string>::iterator it2=it->second.begin(); it2!=it->second.end(); it2++)
        cout<<*it2<<endl;
    cout<<"}\n";
}
于 2012-07-08T09:21:39.643 に答える
1

あなたの難しさはそれ以上の繰り返しだと思います。groups mapを繰り返し処理する例map:

for (it = groups.begin(); it != groups.end(); it++)
{
    // 'it->first' is the 'int' of the map entry (the key)
    //
    cout << "Group " << it->first << "\n";

    // 'it->second' is the 'set<string>' of the map entry (the value)
    //
    for (set<string>::iterator name_it = it->second.begin();
         name_it != it->second.end();
         name_it++)
    {
        cout << "  " << *name_it << "\n";
    }
}
于 2012-07-08T09:21:39.927 に答える