2012-07-08 59 views
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) 
     { 
     } 
} 
+0

是它最后的'for'循环,迭代过''groups'你map'不确定? – hmjd 2012-07-08 09:14:28

+0

是的,我想打印内容,我不知道该怎么做。 – R11G 2012-07-08 13:50:09

回答

1

你的方法很好。通过使用map<int, set<string> >::iterator it,您可以使用it->firstit->second访问给定的<key,value>对。由于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; 
} 
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"; 
} 
1

认为是在groupsmap这是你的困难迭代。迭代的例子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"; 
    } 
}