1

我正在编写一个程序,它从文件中读取团队名称并将它们分组。每组 4 号。我使用的是:

map<int, set<string> > groups

假设团队名称是国家名称。现在在将所有团队名称输入resp之后。组我想打印每个组的内容,这就是我卡住的地方。

这是我迄今为止编写的完整工作代码。

#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>对。由于它本身是一个标准容器,因此您可以使用 an来遍历元素: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

在迭代 astd::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这是你的困难的迭代。迭代 a 的示例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 回答