2012-07-08 62 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"; 
    } 
}