std::find_if 알고리즘 C++

Jinku Hu 2023년10월12일
  1. std::find_if 함수를 사용하여 주어진 기준을 충족하는 요소 검색
  2. std::find_first_of 함수를 사용하여 두 범위에서 일치하는 요소 검색
  3. find_end 함수를 사용하여 구분 기호로 문자열 분할
std::find_if 알고리즘 C++

이 기사에서는 C++ 표준 템플릿 라이브러리에서 std::find_if 알고리즘을 활용하는 방법을 보여줍니다.

std::find_if 함수를 사용하여 주어진 기준을 충족하는 요소 검색

std::find_if 함수는 STL 알고리즘의 일부이며 주어진 조건을 만족하는 범위의 요소를 검색하는 방법을 제공합니다. 즉, 조건은 bool 값을 반환하는 호출 가능한 개체로 지정됩니다.

std::find_if 함수의 기본 오버로드는 검색해야 하는 범위를 나타내는 두 개의 반복자를 허용합니다. 세 번째 매개변수는 범위의 요소를 평가하는 데 사용되는 호출 가능한 개체를 나타냅니다. 범위 반복자는 최소한 LegacyInputIterator 요구 사항을 충족해야 합니다.

std::find_if는 주어진 기준을 만족하는 첫 번째 요소에 대한 반복자를 반환하거나 그러한 요소가 발견되지 않으면 두 번째 인수 반복자를 반환합니다.

다음 코드 스니펫에서 std::string 객체에 std::find_if 알고리즘을 사용하고 isupper 함수를 호출 가능한 객체로 사용합니다. 결과적으로 이 함수는 문자열에 소문자만 포함되어 있는지 여부를 결정하는 데 도움이 됩니다.

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main() {
  string str1 = "this is random String";
  string str2 = "this is";
  string str3 = "wqz";

  std::find_if(begin(str1), end(str1), isupper) != end(str1)
      ? cout << "str1 contains uppercase letters" << endl
      : cout << "str1 contains only lowercase letters" << endl;

  std::find_if(begin(str2), end(str2), isupper) != end(str2)
      ? cout << "str2 contains uppercase letters" << endl
      : cout << "str2 contains only lowercase letters" << endl;

  return EXIT_SUCCESS;
}

출력:

str1 contains uppercase letters
str2 contains only lowercase letters

std::find_first_of 함수를 사용하여 두 범위에서 일치하는 요소 검색

std::find_first_of는 두 개의 주어진 범위에서 동일한 요소를 검색하는 데 사용할 수 있는 STL의 또 다른 강력한 알고리즘입니다. 함수는 4개의 반복자를 매개변수로 받아들이고, 처음 두 개는 마지막 두 개의 반복자 인수로 전달된 요소를 검색해야 하는 범위를 나타냅니다.

후자의 두 반복자는 LegacyForwardIterator의 요구 사항을 충족해야 합니다. 이 경우 std::find_first_of 알고리즘을 사용하여 두 문자열에서 문자가 일치하는지 확인합니다. 함수의 반환 값은 두 번째 범위의 요소와 일치하는 검색된 범위의 첫 번째 요소에 대한 반복기입니다. 그러한 요소가 없으면 검색된 범위의 두 번째 반복자가 반환됩니다.

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main() {
  string str1 = "this is random String";
  string str2 = "this is";
  string str3 = "wqz";

  std::find_first_of(str1.begin(), str1.end(), str2.begin(), str2.end()) ==
          str1.end()
      ? cout << "no letters match in str1 and str2" << endl
      : cout << "some letters match in str1 and str2" << endl;

  std::find_first_of(str2.begin(), str2.end(), str3.begin(), str3.end()) ==
          str2.end()
      ? cout << "no letters match in str2 and str3" << endl
      : cout << "some letters match in str2 and str3" << endl;

  return EXIT_SUCCESS;
}

출력:

some letters match in str1 and str2
no letters match in str2 and str3

find_end 함수를 사용하여 구분 기호로 문자열 분할

반면에 다른 범위에서 주어진 범위 시퀀스의 마지막 항목을 검색하는 find_end 알고리즘이 있습니다. std::find_first_of와 마찬가지로 이 알고리즘은 두 범위를 나타내는 4개의 반복자를 허용하지만 첫 번째 범위에서 정확한 시퀀스 일치를 찾으려고 합니다.

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main() {
  string str1 = "this is random String";
  string str2 = "this is";
  string str3 = "wqz";

  auto ret = std::find_end(str1.begin(), str1.end(), str2.begin(), str2.end());
  ret == str1.end() ? cout << "no such sequence found" << endl
                    : cout << "last occurrence found at "
                           << std::distance(str1.begin(), ret) << endl;

  ret = std::find_end(str2.begin(), str2.end(), str3.begin(), str3.end());
  ret == str2.end() ? cout << "no such sequence found" << endl
                    : cout << "last occurrence found at "
                           << std::distance(str2.begin(), ret) << endl;

  return EXIT_SUCCESS;
}

출력:

last occurrence found at 0
no such sequence found
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - C++ Algorithm