컨테이너에서 특정 값을 검색하는 데 사용되는 알고리즘 함수다.
std::find는 순차 탐색을 수행하므로 시간 복잡도는 O(n)이다.
정렬된 컨테이너에서 더 빠른 탐색이 필요할 경우 std::binary_search나 std::lower_bound, std::upper_bound와 같은 함수가 더 적합하다.
#include <algorithm>
std::find(시작_반복자, 끝_반복자, 검색_값);
#include <iostream>
#include <vector>
#include <algorithm> // std::find
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
// 값 30을 찾기
auto it = std::find(vec.begin(), vec.end(), 30);
if (it != vec.end()) {
std::cout << "Found: " << *it << "\n";
} else {
std::cout << "Not Found\n";
}
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
// 값 60을 찾기
auto it = std::find(vec.begin(), vec.end(), 60);
if (it != vec.end()) {
std::cout << "Found: " << *it << "\n";
} else {
std::cout << "Not Found\n";
}
return 0;
}
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "Hello, World!";
// 문자 'o'를 찾기
auto it = std::find(str.begin(), str.end(), 'o');
if (it != str.end()) {
std::cout << "Found: " << *it << " at index " << (it - str.begin()) << "\n";
} else {
std::cout << "Not Found\n";
}
return 0;
}
#include <iostream>
#include <algorithm>
int main() {
int arr[] = {5, 10, 15, 20, 25};
int n = sizeof(arr) / sizeof(arr[0]);
// 값 15를 찾기
auto it = std::find(arr, arr + n, 15);
if (it != arr + n) {
std::cout << "Found: " << *it << " at index " << (it - arr) << "\n";
} else {
std::cout << "Not Found\n";
}
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
struct Person {
std::string name;
int age;
};
// 비교 연산자 오버로딩
bool operator==(const Person &p1, const Person &p2) {
return p1.name == p2.name && p1.age == p2.age;
}
int main() {
std::vector<Person> people = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 35}};
// 찾고자 하는 사람
Person target = {"Bob", 30};
auto it = std::find(people.begin(), people.end(), target);
if (it != people.end()) {
std::cout << "Found: " << it->name << ", Age: " << it->age << "\n";
} else {
std::cout << "Not Found\n";
}
return 0;
}
std::find는 순차 탐색을 수행하므로 시간 복잡도는 O(n)이다.
정렬된 컨테이너에서 더 빠른 탐색이 필요할 경우 std::binary_search나 std::lower_bound, std::upper_bound와 같은 함수가 더 적합하다.