我正在编写一个程序,从文件中读取团队名称并将其分组。每组尺寸为 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)
{
}
}
你的做法很好。通过使用map<int, set<string> >::iterator it
您可以访问给定的<key,value>
与it->first
and it->second
. Since set<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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)