string::find()와 algorithm::find() 차이

김민수·2025년 1월 8일

C++

목록 보기
5/68

string::find()<algorithm> 헤더의 std::find() 함수는 모두 검색이라는 공통된 기능을 수행하지만, 사용 방법과 동작 방식에서 차이가 있다.

1. string::find()


  • string::find()std::string 클래스의 멤버 함수로, 문자열 내에서 특정 문자 또는 문자열을 찾을 때 사용된다.
  • 반환값은 찾은 첫 번째 위치의 인덱스이며, 찾지 못할 경우 std::string::npos를 반환한다.

⦁ 함수 시그니처

size_t find(const std::string& str, size_t pos = 0) const;
size_t find(const char* s, size_t pos = 0) const;
size_t find(char c, size_t pos = 0) const;

⦁ 예시

int main() {
    std::string str = "Hello, World!";
    
    // 문자열 찾기
    size_t pos = str.find("World");
    if (pos != std::string::npos) {
        std::cout << "'World' found at position: " << pos << std::endl;
    } else {
        std::cout << "'World' not found!" << std::endl;
    }

    // 문자 찾기
    size_t charPos = str.find('o');
    std::cout << "'o' found at position: " << charPos << std::endl;

    return 0;
}
  • string::find()std::string 객체에서만 사용할 수 있는 멤버 함수다.
  • 검색 결과로 찾은 위치의 인덱스를 반환하며, 찾지 못하면 std::string::npos를 반환한다.
  • 찾고자 하는 대상이 문자, 문자열, C 문자열 등 다양한 형태일 때 사용할 수 있도록 여러 버전이 제공된다.


2. <algorithm>의 std::find()


  • std::find()<algorithm> 헤더에 정의된 범용 알고리즘 함수로, 임의의 컨테이너에서 특정 요소를 찾을 때 사용된다.
  • 반환값은 찾은 요소를 가리키는 이터레이터이며, 요소를 찾지 못할 경우 컨테이너의 end() 이터레이터를 반환한다.

⦁ 함수 시그니처

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

⦁ 예시

#include <algorithm>

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

    // std::find()로 값 찾기
    auto it = std::find(vec.begin(), vec.end(), 3);
    if (it != vec.end()) {
        std::cout << "Found 3 at index: " << std::distance(vec.begin(), it) << std::endl;
    } else {
        std::cout << "3 not found!" << std::endl;
    }

    return 0;
}
  • 검색 결과로 찾은 요소를 가리키는 이터레이터를 반환하며, 찾지 못할 경우 end() 이터레이터를 반환한다.
  • 입력으로 이터레이터 범위를 받으며, 템플릿 함수로 구현되어 모든 STL 컨테이너(vector, list, array 등)에서 동작한다.
profile
안녕하세요

0개의 댓글