打印地图中包含的集合内容 [英] Printing contents of sets included in a map

查看:53
本文介绍了打印地图中包含的集合内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序从文件中读取团队名称并将其分为几组.每组大小为4.我使用的是:

I am writing a program that reads team names from a file and divides them into groups. Each group of size 4. I am using a:

map<int, set<string> > groups

假设团队名称为国家/地区名称.现在将所有团队名称输入后.我想打印每个组的内容,这就是我遇到的困难.

Assume the team names to be countries names. Now after entering all the team names into the resp. groups I want to print the contents of each group and this is where I am getting stuck.

这是我到目前为止编写的完整的工作代码.

Here is the full working code, I have written so far.

#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)
        {
        }
}

推荐答案

您的方法很好.通过使用 map< int,设置< string>> :: iterator ,您可以通过 it-> first it->>访问给定的< key,value> 对; second .由于 set< string> 本身是标准容器,因此您可以使用 set< string> :: iterator 遍历元素:

Your approach is fine. By using map<int, set<string> >::iterator it you can access a the given <key,value> pair with it->first and it->second. Since set<string> is a standard container itself you can use an set<string>::iterator to traverse through the elements:

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;
}

这篇关于打印地图中包含的集合内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆