[c++] 조건자(predicate) 활용

C++의 조건자(predicate)는 일반적으로 함수나 함수 객체로 나타내는 조건을 캡슐화하는 데 사용됩니다. 조건자는 주로 알고리즘 함수와 함께 사용되어 원소를 필터링하거나 정렬하는 데 사용됩니다. 이 포스트에서는 C++에서 조건자를 활용하는 몇 가지 예제를 살펴보겠습니다.

조건자 사용 예제

1. std::find_if를 사용한 요소 검색

std::find_if 알고리즘은 조건자를 사용하여 범위 내에서 조건을 만족하는 첫 번째 요소를 검색합니다. 아래는 조건자를 사용하여 벡터에서 특정 값보다 큰 첫 번째 요소를 검색하는 예제입니다.

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

bool isGreaterThan(int threshold, int value) {
    return value > threshold;
}

int main() {
    std::vector<int> numbers = {1, 3, 5, 7, 9};
    int threshold = 4;
    auto it = std::find_if(numbers.begin(), numbers.end(), std::bind(isGreaterThan, threshold, std::placeholders::_1));
    if (it != numbers.end()) {
        std::cout << "첫 번째로 " << threshold << "보다 큰 수: " << *it << std::endl;
    } else {
        std::cout << threshold << "보다 큰 수를 찾지 못했습니다." << std::endl;
    }
    return 0;
}

2. std::remove_if를 사용한 요소 제거

std::remove_if 알고리즘은 조건자를 사용하여 범위 내에서 조건을 만족하는 요소를 제거합니다. 아래 예제는 조건자를 사용하여 벡터에서 홀수를 제거하는 방법을 보여줍니다.

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

bool isOdd(int value) {
    return value % 2 != 0;
}

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    numbers.erase(std::remove_if(numbers.begin(), numbers.end(), isOdd), numbers.end());
    std::cout << "짝수만 남은 벡터: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}

결론

C++의 조건자는 알고리즘 함수와 함께 사용하여 다양한 작업을 수행하는 데 유용합니다. 조건자는 함수 또는 함수 객체로 정의되므로 유연하게 기능을 확장하고 조합할 수 있습니다. 이를 통해 코드를 더 간결하고 가독성있게 작성할 수 있습니다.

참고 문헌: cplusplus.com