2012-07-08 3 views
1

파일에서 팀 이름을 읽고이를 그룹으로 나누는 프로그램을 작성 중입니다. 각 그룹 크기는 다음과 같습니다.지도에 포함 된 세트 내용 인쇄

map<int, set<string> > groups 

팀 이름을 국가 이름으로 가정합니다. resp에 모든 팀 이름을 입력 한 후 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) 
     { 
     } 
} 
+0

인가? – hmjd

+0

네. 그 내용을 인쇄하고 싶습니다. 어떻게해야할지 모르겠습니다. – R11G

답변

1

귀하의 접근 방법은 문제가 없습니다. map<int, set<string> >::iterator it을 사용하면 it->firstit->second으로 주어진 <key,value> 쌍에 액세스 할 수 있습니다. set<string> 표준 컨테이너 자체이기 때문에 당신이 요소를 통해 통과하는 set<string>::iterator을 사용할 수 있습니다하십시오 std::map<..>를 반복하는 동안

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

, 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` 루프, 당신은 모를지도`은`groups``를 통해 반복

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