string::find()와 <algorithm> 헤더의 std::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를 반환한다.<algorithm>의 std::find()std::find()는 <algorithm> 헤더에 정의된 범용 알고리즘 함수로, 임의의 컨테이너에서 특정 요소를 찾을 때 사용된다.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;
}
vector, list, array 등)에서 동작한다.