'C++' std::find, std::find_if, std::find_if_not

토스트·2024년 12월 25일

'C++' std::algorithm

목록 보기
3/11

find

template<class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value); //constexpr since C++20

C++17 ~

template<class ExecutionPolicy, class ForwardIt, class T>
ForwardIt find(ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, const T& value);

: 주어진 범위에서 특정 값을 찾는 데 사용됩니다. 특정 값을 찾으면 해당 요소를 가리키는 반복자를 반환하고, 찾지 못한다면 last를 반환합니다.

  • first : 탐색을 시작할 첫 번째 요소를 가리키는 입력 반복자 실행 정책에 따라 순방향 반복자
  • last : 탐색을 종료할 마지막 번째 요소의 다음 위치를 가리키는 입력 반복자 실행 정책에 따라 순방향 반복자
  • value : 찾고자 하는 값
  • policy : 실행 정책

실행 정책은 std::execution 헤더에 포함되어있습니다.

  • execution::seq : 순차 실행 (기본 값)
  • execution::par : 병렬 실행 (멀티코어 시스템에서 작업이 병렬로 수행됩니다.)
  • execution::par_unseq : 병렬 및 비순차 실행

<example>

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

using namespace std;

int main() {
	vector<int> vec = {1, 2, 3, 4, 5};
    
    cout << *find(vec.begin(), vec.begin() + 2, 5) << endl; 
    // 해당 범위에서 값을 찾지 못해 last를 반환합니다.
    
    auto it = find(vec.begin(), vec.end(), 4);
    
    it != vec.end() ? cout << *it : cout << "Not Found";
    

	return 0;
}

결과값

find_if

template<class InputIt, class UnaryPred>
InputIt find_if(InputIt first, InputIt last, UnaryPred p); // constexpr since C++20

C++17 ~

template<class ExecutionPolicy, class ForwardIt, class UnaryPred>
ForwardIt find_if(ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPred p);

: 주어진 범위에서 특정 조건을 만족하는 값을 찾는 데 사용됩니다. 조건을 만족하는 값을 찾으면 해당 요소를 가리키는 반복자를 반환하고, 찾지 못한다면 last를 반환합니다.

find_if_not

C++11

template<class InputIt, class UnaryPred>
InputIt find_if_not(InputIt first, InputIt last, UnaryPred q); //constexpr since C++20

C++17 ~

template<class ExecutionPolicy, class ForwardIt, class UnaryPred>
ForwardIt find_if_not(ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPred q);

: 주어진 범위에서 특정 조건을 만족하지 못하는 값을 찾는 데 사용됩니다. 조건을 만족하지 못하는 값을 찾으면 해당 요소를 가리키는 반복자를 반환하고, 찾지 못한다면 last를 반환합니다.

  • first : 탐색을 시작할 첫 번째 요소를 가리키는 입력 반복자 실행 정책에 따라 순방향 반복자
  • last : 탐색을 종료할 마지막 번째 요소의 다음 위치를 가리키는 입력 반복자 _실행 정책에 따라 순방향 반복자
  • p : 각 요소에 적용할 조건 함수 또는 함수 객체 (true일 때 반환)
  • q : 각 요소에 적용할 조건 함수 또는 함수 객체 (false일 때 반환)
  • policy : 실행 정책

실행 정책은 std::execution 헤더에 포함되어있습니다.

  • execution::seq : 순차 실행 (기본 값)
  • execution::par : 병렬 실행 (멀티코어 시스템에서 작업이 병렬로 수행됩니다.)
  • execution::par_unseq : 병렬 및 비순차 실행

<example>

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

using namespace std;

int main() {
    vector<int> vec = { 1, 2, 3, 4, 5 };

    cout << *find_if(vec.begin(), vec.end(), [](const int& x) {return x > 3; }) << endl;
    
    cout << *find_if_not(vec.begin(), vec.end(), [](const int& x) {return x < 3; }) << endl;

    return 0;
}

결과값

0개의 댓글