💡 퀵 접속: cpp.kr/find_first_of
C++ 표준 라이브러리의 알고리즘으로, 첫 번째 범위에서 두 번째 범위의 요소 중 하나와 일치하는 첫 번째 요소를 찾습니다. 기본적으로 == 연산자를 사용하여 비교하며, 커스텀 비교 함수를 제공할 수 있습니다.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> haystack = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<int> needles = {5, 7, 9};
// needles의 요소 중 하나와 일치하는 첫 번째 요소 찾기
auto it = std::find_first_of(haystack.begin(), haystack.end(),
needles.begin(), needles.end());
if (it != haystack.end()) {
std::cout << "needles의 요소와 일치하는 첫 번째 요소를 찾았습니다: "
<< *it << " (위치: " << std::distance(haystack.begin(), it) << ")" << std::endl;
} else {
std::cout << "needles의 요소와 일치하는 요소를 찾지 못했습니다." << std::endl;
}
return 0;
}
실행 결과:
needles의 요소와 일치하는 첫 번째 요소를 찾았습니다: 5 (위치: 4)
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
int main() {
std::vector<double> haystack = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0};
std::vector<double> needles = {2.1, 4.1, 6.1};
// 두 실수가 거의 같은지 비교하는 함수
auto almost_equal = [](double a, double b) {
return std::abs(a - b) < 0.2;
};
auto it = std::find_first_of(haystack.begin(), haystack.end(),
needles.begin(), needles.end(),
almost_equal);
if (it != haystack.end()) {
std::cout << "거의 일치하는 첫 번째 요소를 찾았습니다: "
<< *it << " (위치: " << std::distance(haystack.begin(), it) << ")" << std::endl;
} else {
std::cout << "거의 일치하는 요소를 찾지 못했습니다." << std::endl;
}
return 0;
}
실행 결과:
거의 일치하는 첫 번째 요소를 찾았습니다: 2 (위치: 1)
#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}
};
std::vector<Person> targets = {
{"Charlie", 30},
{"Eve", 40},
{"Frank", 45}
};
// targets의 요소 중 하나와 일치하는 첫 번째 요소 찾기
auto it = std::find_first_of(people.begin(), people.end(),
targets.begin(), targets.end());
if (it != people.end()) {
std::cout << "targets의 요소와 일치하는 첫 번째 요소를 찾았습니다: "
<< it->name << " (" << it->age << "세)"
<< " (위치: " << std::distance(people.begin(), it) << ")" << std::endl;
} else {
std::cout << "targets의 요소와 일치하는 요소를 찾지 못했습니다." << std::endl;
}
return 0;
}
실행 결과:
targets의 요소와 일치하는 첫 번째 요소를 찾았습니다: Charlie (30세) (위치: 2)
| 함수 | 설명 |
|---|---|
| find_first_of(first1, last1, first2, last2) | 기본 비교 연산자를 사용하여 두 번째 범위의 요소 중 하나와 일치하는 첫 번째 요소를 찾음 |
| find_first_of(first1, last1, first2, last2, binary_pred) | 커스텀 비교 함수를 사용하여 두 번째 범위의 요소 중 하나와 일치하는 첫 번째 요소를 찾음 |