[C++] 문자열 리스트(Vector, 배열) 정렬

여러 문자열들을 알파벳 순서로 정렬하거나, 문자열의 길이로 정렬하고 싶을 때가 있습니다. 또는 자신만의 어떤 기준으로 정렬해야할 때가 있습니다. 이 글에서는 vector 또는 배열에 저장된 std::string 객체들을 오름차순, 내림차순으로 정렬하는 방법을 소개합니다.

1. 문자열 Vector 정렬

vector에 저장된 문자열들은 std::sort()로 정렬할 수 있습니다. sort(first, last)처럼 정렬하려는 요소의 시작, 끝을 입력해주면 정렬이 됩니다.

1.1 알파벳 순서로 오름차순 정렬

문자열의 경우, 정렬 규칙(comparator)를 설정하지 않으면 기본적으로 알파벳 순서로 문자열을 오름차순으로 정렬합니다.

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

int main() {
    std::vector<std::string> arr = { "melon", "watermelon",
            "kiwi", "apple", "banana", "mango", "peach"};

    std::sort(arr.begin(), arr.end());

    for (const auto &item : arr) {
        std::cout << item << std::endl;
    }
}

Output:

apple
banana
kiwi
mango
melon
peach
watermelon

1.2 알파벳 순서로 내림차순 정렬 (1)

sort 함수는 sort(first, last, comp) 처럼 인자로 comparator를 전달하여 어떻게 정렬할지 정렬 규칙을 직접 설정할 수 있습니다.

단순히 오름차순을 내림차순으로만 변경하려면, 미리 정의된 std::greater라는 comparator를 인자로 전달하면 됩니다.

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

int main() {
    std::vector<std::string> arr = { "melon", "watermelon",
            "kiwi", "apple", "banana", "mango", "peach"};

    std::sort(arr.begin(), arr.end(), std::greater<>());

    for (const auto &item : arr) {
        std::cout << item << std::endl;
    }
}

Output:

watermelon
peach
melon
mango
kiwi
banana
apple

1.3 알파벳 순서로 내림차순 정렬 (2)

comparator를 전달할 때, 미리 정의된 std::greater를 사용하지 않고 직접 구현하고 싶다면, 아래와 같이 구현할 수 있습니다. 실행 결과는 동일합니다.

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

struct greater
{
    bool operator()(std::string const &a, std::string const &b) const
    {
        return a > b;
    }
};

int main() {
    std::vector<std::string> arr = { "melon", "watermelon",
            "kiwi", "apple", "banana", "mango", "peach"};

    std::sort(arr.begin(), arr.end(), greater());

    for (const auto &item : arr) {
        std::cout << item << std::endl;
    }
}

1.4 알파벳 순서로 내림차순 정렬 (3)

comparator를 구현할 때 아래와 같이 Lambda를 사용하여 구현할 수 있습니다. 실행 결과는 동일합니다.

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

int main() {
    std::vector<std::string> arr = { "melon", "watermelon",
            "kiwi", "apple", "banana", "mango", "peach"};

    std::sort(arr.begin(), arr.end(),
            [](std::string a, std::string b) { return a > b; });

    for (const auto &item : arr) {
        std::cout << item << std::endl;
    }
}

1.5 문자열 길이 순서로 내림차순 정렬

comparator를 직접 구현하여 문자열 길이 순서로 정렬할 수 있습니다.

아래 예제는 문자열 길이 순서로 내림차순 정렬하는 예제입니다.

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

int main() {
    std::vector<std::string> arr = { "melon", "watermelon",
            "kiwi", "apple", "banana", "mango", "peach"};

    std::sort(arr.begin(), arr.end(),
            [](std::string a, std::string b) { return a.size() > b.size(); });

    for (const auto &item : arr) {
        std::cout << item << std::endl;
    }
}

Output:

watermelon
banana
melon
apple
mango
peach
kiwi

오름차순으로 정렬하거나, 다른 기준으로 정렬하려면 comparator를 자신의 목적에 맞게 수정하시면 됩니다.

2. 문자열 배열 정렬

배열 정렬도 vector 정렬과 동일하게 std:sort()를 사용할 수 있습니다. 배열의 경우도 sort(first, last)처럼 정렬할 요소의 첫번째와 마지막을 입력해야하는데요. 배열의 주소를 입력하면 됩니다. 마지막의 배열 주소를 찾기 위해 아래와 같이 배열의 size를 계산하고 첫번째 요소에서 size를 더해 마지막 요소의 주소 값을 알아낼 수 있습니다.

2.1 알파벳 순서로 오름차순 정렬

아래와 같이 배열을 알파벳 순서로 오름차순 정렬할 수 있습니다.

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

int main() {

    std::string arr[7] = {"melon", "watermelon",
            "kiwi", "apple", "banana", "mango", "peach"};
    int size = (sizeof(arr)/sizeof(*arr));

    std::sort(arr, arr + size);

    for (const auto &item : arr) {
        std::cout << item << std::endl;
    }
}

Output:

apple
banana
kiwi
mango
melon
peach
watermelon

2.2 내림차순 정렬

vector 정렬과 같은 방식으로, std::greater 객체를 comparator로 전달하여 내림차순 정렬할 수 있습니다.

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

int main() {

    std::string arr[7] = {"melon", "watermelon",
            "kiwi", "apple", "banana", "mango", "peach"};
    int size = (sizeof(arr)/sizeof(*arr));

    std::sort(arr, arr + size, std::greater<>());

    for (const auto &item : arr) {
        std::cout << item << std::endl;
    }
}

Output:

watermelon
peach
melon
mango
kiwi
banana
apple

3. References

Loading script...
codechachaCopyright ©2019 codechacha