반응형

map 자료 구조를 통해 특정 문자나 단어의 등장횟수를 쉽게 셀 수 있다.

 

1. 알파벳 등장 횟수 출력하기

#include <bits/stdc++.h>
using namespace std;

int main(){
	freopen("input.txt","rt",stdin);
	ios::sync_with_stdio(false);
	cin.tie(0);
	map<char, int> ch;
	map<char, int>::iterator it;
	
	char a[100];
	cin >> a; 
	
	for(int i=0; i<a[i]!='\0'; i++){
		ch[a[i]]++;
	}
	
	for(it=ch.begin(); it!=ch.end(); it++){
		cout << it->first << " " << it->second<<'\n';
	}
	


}

map 자료구조를 이용할 때는 자료에 대해

 

이터레이터로 접근할 수 있다.

 

input

aaaabbbcdcdcaa

 

output

a 6
b 3
c 3
d 2

 

 

 

2. 단어 등장 횟수 출력하기

#include <bits/stdc++.h>
using namespace std;

int main(){
	freopen("input.txt","rt",stdin);
	ios::sync_with_stdio(false);
	cin.tie(0);
	map<string, int> ch;
	map<string, int>::iterator it;
	string s;
	int n;
	cin >> n;
	for(int i=0; i<n; i++){
		cin>>s;
		
		ch[s]++;
	}
	
	
	for(it=ch.begin(); it!=ch.end(); it++){
		cout << it->first << ' '<<it->second << '\n';
		
	}
	
	

}

input---

7
book
dog
cat
dog
cat
book
cat

 

 

output----

book 2
cat 3
dog 2

+ Recent posts