[C++] 백준 4358 - 생태학

혜원·2022년 9월 26일
0

백준

목록 보기
2/25

백준 4358-생태학

문제

코드

#include<iostream>
#include<algorithm>
#include<map>

using namespace std;

int main() {
	cin.tie(NULL);
	cout.tie(NULL);
	ios::sync_with_stdio(false);

	char input[51];
	double total = 0;
	map<string, double> tree;
	map<string, double>::iterator iter;

	while (1) {
		cin.getline(input, 50);
		if (cin.eof() == true) {
			break;
		}
		if (tree.count(input) > 0) {
			tree[input]++;
		}
		else {
			tree[input] = 1;
		}
		total++;
	}

	for (iter = tree.begin(); iter != tree.end(); iter++) {
		cout << fixed;
		cout.precision(4);
		cout << iter->first << " " << iter->second / total * 100 << "\n";
	}
	
}

해설

1. Map 사용

-Map은 Key, Value 쌍의 데이터가 트리형태로 저장되는 자료구조이다.
-Map의 key 값은 unique하다.
-map.count를 이용하여 현재 map에 key값이 존재하는지를 알아볼 수 있다.
-map은 저장될 때 key값에 의해 자동으로 정렬된다.
-마지막으로 출력할 때는 iterator을 이용하여 for문으로 출력하였다.

2. 소수점 출력

cout << fixed;
cout.precision(4);

cout.precision(4)만 써주면 정수와 소수점을 합하여 4자리가 출력되므로 cout<<fixed를 써줘야한다.

3. EOF로 종료

profile
안녕하세요

0개의 댓글