스스로 공부하기/C++

[C++] vector 이용해 string, int 저장하기 (1181 단어정렬 - C++)

Seohyeong Lee 2022. 9. 18. 17:59

https://blockdmask.tistory.com/64

 

[C++] Pair 클래스 정리 및 예제 (vector, sort)

안녕하세요!  BlockDMask 입니다. 이번에는 C++의 Pair 클래스에 대해 간단히 정리 해보려합니다. 클래스사용법, 함수 및 간단한 예제를 준비해봤습니다. 감사합니다. 1) Pair 클래스란. 두 객체를 하

blockdmask.tistory.com

문자열을 pair에 저장할 수 있다. 단, string 헤더 파일을 포함시켜 string을 사용해야 함.

https://boycoding.tistory.com/178

 

C++ 05.03 - 문자열, std::string

05.03 - 문자열, std::string 처음으로 작성한 C++ 프로그램은 다음과 같다. #include int main() { std::cout << "Hello, world!" << std::endl; return 0; } "Hello, world!"는 정확히 뭘까? "Hello, world!"는..

boycoding.tistory.com

#include <algorithm>
#include <vector>
#include <iostream>
#include <utility>
#include <string>

using namespace std;

bool compare(pair <string,int> p1, pair <string,int>p2) {
	if (p1.second == p2.second) {
		return p1.first < p2.first;
	}
	return p1.second < p2.second;
}

int main(){
	vector <pair <string, int> > a;
	
	int n; 
	cin >> n;
	
	int temp = n;
	
	string t1;
	int t2;
	while (n--){
		cin >> t1;
		t2 = t1.length();
		a.push_back(make_pair(t1, t2));
	}
	
	sort (a.begin(), a.end(), compare);
	int i;
	for(i=0; i<temp-1; i++){
		if (a[i].first != a[i+1].first) cout << a[i].first << "\n";
	}
	cout << a[temp-1].first;
}