모두의 코드
C++ 레퍼런스 - find 함수 (<algorithm>)

작성일 : 2019-01-19 이 글은 92127 번 읽혔습니다.

아직 C++ 에 친숙하지 않다면 씹어먹는 C++ 은 어때요?

find

<algorithm> 에 정의됨

template <class InputIterator, class T>
InputIterator find(InputIterator first, InputIterator last, const T& val);

범위 안에 원하는 값을 찾는다.

범위 안 (first 부터 last 전 까지) 의 원소들 중 val 과 일치하는 첫 번째 원소를 가리키는 반복자를 리턴합니다. 만일 일치하는 원소를 찾지 못할 경우 last 를 리턴합니다.

이 함수는 원소를 비교할 때 operator== 을 사용합니다.

참고로 이 함수는 stringfind 함수와 다릅니다.

인자들

  • first, last : 원소들의 시작과 끝을 가리키는 반복자들. 이 때 확인하는 범위는 [first, last) 로 정의됩니다. first 가 가리키는 원소는 포함되지만 last 가 가리키는 원소는 포함되지 않습니다.

  • val : 비교할 값. 이 때 val 의 타입 T 의 경우 operator== 가 정의되어 있어야만 합니다.

리턴값

첫 번째로 일치하는 원소를 가리키는 반복자. 일치하는 원소가 없을 경우 last 가 리턴됩니다.

구현 예시

template <class InputIt, class T>
constexpr InputIt find(InputIt first, InputIt last, const T& value) {
  for (; first != last; ++first) {
    if (*first == value) {
      return first;
    }
  }
  return last;
}

실행 예제

// find example
#include <algorithm>  // std::find
#include <iostream>   // std::cout
#include <vector>     // std::vector

int main() {
  // using std::find with array and pointer:
  int myints[] = {10, 20, 30, 40};
  int* p;

  p = std::find(myints, myints + 4, 30);
  if (p != myints + 4)
    std::cout << "Element found in myints: " << *p << '\n';
  else
    std::cout << "Element not found in myints\n";

  // using std::find with vector and iterator:
  std::vector<int> myvector(myints, myints + 4);
  std::vector<int>::iterator it;

  it = find(myvector.begin(), myvector.end(), 30);
  if (it != myvector.end())
    std::cout << "Element found in myvector: " << *it << '\n';
  else
    std::cout << "Element not found in myvector\n";

  return 0;
}

실행 결과

실행 결과

Element found in myints: 30
Element found in myvector: 30

참고 자료

  • search : 어떤 원소들의 나열을 검색한다.

  • binary_search : 특정 값과 일치하는 원소를 찾습니다. (이진 탐색으로)

  • for_each : 범위 안에 원소들에 대해 함수를 호출해준다.

첫 댓글을 달아주세요!
프로필 사진 없음
강좌에 관련 없이 궁금한 내용은 여기를 사용해주세요

    댓글을 불러오는 중입니다..