<언어>/[C++]

[C++] sorting

콜리브리 2020. 12. 6. 16:03
Custom sort

직접 compare 함수를 만들어서 여러 기준으로 데이터 정렬 가능.

(lambda 사용하면 inline으로 더 깔끔하게 작성할 수 있음) 

 

String vector 정렬 시, 길이를 기준으로 먼저 정렬 한 후, 같은 길이끼린 사전순으로 정렬하기

// Compare length first, then alphabetical order
bool comp_len_alpha(string& a, string& b) {
	if (a.size() == b.size())
		return a < b;
	return a.size() < b.size();
}

sort(str_vec.begin(), str_vec.end(), comp_len_alpha)

 

 

- Sorting two vectors simulatenously

Sorting A and B together :

1. Make copy of A, called 'c_A'.

First, sort A (let's call the sorted result 's_A').

Now, compare c_A with s_A to figure out the order for each element of B. Then sort manually.

 

2. Combine two into one container (pair, struct, class). Sort the vector of container using custom sort on one standard

→ 두 벡터에 들어있는 내용물들 꺼내서 하나의 컨테이너로 합치는데 O(N), 정렬에 O(NlogN), 정렬한 결과를 기존 벡터로 집어넣는데 O(N)

 

String인 이름을 사전순으로 정렬하며, Double형 나이도 함께 정렬하는 코드

class Name_pairs {
	vector<string> name;
	vector<double> age;

public:
	void read_names();
	void read_ages();
	void print();
	void sort();
};

void Name_pairs::sort() {
	struct sort_pair {
		string name;
		double age;
	};

	cout << "--Sorting--\n";

	// 1. 두 벡터에 들어있는 내용물들 꺼내서 struct으로 합치기
	vector<sort_pair> v;
	for (int i = 0; i < name.size(); i++) {
		v.push_back({ name[i], age[i] });
	}
	
	// 2. 정렬
	std::sort(v.begin(), v.end(), [](sort_pair& a, sort_pair& b) {return a.name < b.name; });
	
	// 3. 정렬한 결과를 원래 벡터에 집어넣기
	name.clear(); age.clear();
	for (int i = 0; i < v.size(); i++) {
		name.push_back(v[i].name);
		age.push_back(v[i].age);
	}

	std::cout << "--Complete--\n";
}

 

stackoverflow.com/questions/34878329/how-to-sort-two-vectors-simultaneously-in-c-without-using-boost-or-creating-te

stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects

 

Template 배운 후 공부!