[BOJ]1181 - 단어 정렬

yoon_H·2022년 5월 8일

BOJ

목록 보기
1/110

1181

전체 코드

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

bool compare(string a, string b)
{
	if (a.length() < b.length())
	{
		return true;
	}
	else if (a.length() > b.length())
		return false;
	else
	{
		for (int i = 0; i < a.length(); i++)
		{
			if (a[i] < b[i])
				return true;
			else if (a[i] > b[i])
				return false;
		}
		return false;
	}
	
}

int main() {
	int n{ 0 };

	cin >> n;

	vector <string> words(n);


	for (int i = 0; i < n; i++)
		cin >> words[i];

	sort(words.begin(), words.end(), compare);
	words.erase(unique(words.begin(), words.end()), words.end());

	for (int i = 0; i < words.size(); i++)
		cout << words[i] << "\n";

}

Sort 메서드에서 comparator로 들어오는 매개함수는 반드시 Strict Weak Ordering을 만족해야 한다.
A == B일 경우에는 A < Bfalse이고 A > B도 false여야 한다는 말이다.

또, vector에서 중복을 제거할 때는

words.erase(unique(words.begin(), words.end()), words.end());

eraseunique 함수를 사용한다.

참고자료

Invalid comparator
vector 중복제거

0개의 댓글