💡 퀵 접속: cpp.kr/find
C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 특정 값을 찾습니다. 기본적으로 == 연산자를 사용하여 비교하며, 첫 번째로 일치하는 요소의 반복자를 반환합니다.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5, 3, 6, 7, 3, 8};
// 3을 찾기
auto it1 = std::find(v.begin(), v.end(), 3);
if (it1 != v.end()) {
std::cout << "3을 찾았습니다. 위치: "
<< std::distance(v.begin(), it1) << std::endl;
} else {
std::cout << "3을 찾지 못했습니다." << std::endl;
}
// 9를 찾기
auto it2 = std::find(v.begin(), v.end(), 9);
if (it2 != v.end()) {
std::cout << "9를 찾았습니다. 위치: "
<< std::distance(v.begin(), it2) << std::endl;
} else {
std::cout << "9를 찾지 못했습니다." << std::endl;
}
return 0;
}
실행 결과:
3을 찾았습니다. 위치: 2 9를 찾지 못했습니다.
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "Hello, World!";
// 'o'를 찾기
auto it1 = std::find(str.begin(), str.end(), 'o');
if (it1 != str.end()) {
std::cout << "'o'를 찾았습니다. 위치: "
<< std::distance(str.begin(), it1) << std::endl;
} else {
std::cout << "'o'를 찾지 못했습니다." << std::endl;
}
// 'z'를 찾기
auto it2 = std::find(str.begin(), str.end(), 'z');
if (it2 != str.end()) {
std::cout << "'z'를 찾았습니다. 위치: "
<< std::distance(str.begin(), it2) << std::endl;
} else {
std::cout << "'z'를 찾지 못했습니다." << std::endl;
}
return 0;
}
실행 결과:
'o'를 찾았습니다. 위치: 4 'z'를 찾지 못했습니다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
struct Person {
std::string name;
int age;
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
};
int main() {
std::vector<Person> people = {
{"Alice", 20},
{"Bob", 25},
{"Charlie", 30},
{"David", 35},
{"Eve", 40}
};
Person target = {"Charlie", 30};
// target과 동일한 Person 찾기
auto it = std::find(people.begin(), people.end(), target);
if (it != people.end()) {
std::cout << "target과 동일한 Person을 찾았습니다. 위치: "
<< std::distance(people.begin(), it) << std::endl;
std::cout << "이름: " << it->name << ", 나이: " << it->age << std::endl;
} else {
std::cout << "target과 동일한 Person을 찾지 못했습니다." << std::endl;
}
return 0;
}
실행 결과:
target과 동일한 Person을 찾았습니다. 위치: 2 이름: Charlie, 나이: 30
| 함수 | 설명 |
|---|---|
| find(first, last, value) | 주어진 범위에서 value와 일치하는 첫 번째 요소를 찾음 |