💡 퀵 접속: cpp.kr/find_if
C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 특정 조건을 만족하는 첫 번째 요소를 찾습니다. 조건은 단항 술어 함수로 제공되며, 조건을 만족하는 첫 번째 요소의 반복자를 반환합니다.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 짝수 찾기
auto it1 = std::find_if(v.begin(), v.end(),
[](int n) { return n % 2 == 0; });
if (it1 != v.end()) {
std::cout << "첫 번째 짝수를 찾았습니다: " << *it1 << std::endl;
} else {
std::cout << "짝수를 찾지 못했습니다." << std::endl;
}
// 5보다 큰 수 찾기
auto it2 = std::find_if(v.begin(), v.end(),
[](int n) { return n > 5; });
if (it2 != v.end()) {
std::cout << "5보다 큰 첫 번째 수를 찾았습니다: " << *it2 << std::endl;
} else {
std::cout << "5보다 큰 수를 찾지 못했습니다." << std::endl;
}
return 0;
}
실행 결과:
첫 번째 짝수를 찾았습니다: 2 5보다 큰 첫 번째 수를 찾았습니다: 6
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
std::string str = "Hello, World!";
// 대문자 찾기
auto it1 = std::find_if(str.begin(), str.end(),
[](char c) { return std::isupper(c); });
if (it1 != str.end()) {
std::cout << "첫 번째 대문자를 찾았습니다: " << *it1 << std::endl;
} else {
std::cout << "대문자를 찾지 못했습니다." << std::endl;
}
// 공백 찾기
auto it2 = std::find_if(str.begin(), str.end(),
[](char c) { return std::isspace(c); });
if (it2 != str.end()) {
std::cout << "첫 번째 공백을 찾았습니다. 위치: "
<< std::distance(str.begin(), it2) << std::endl;
} else {
std::cout << "공백을 찾지 못했습니다." << std::endl;
}
return 0;
}
실행 결과:
첫 번째 대문자를 찾았습니다: H 첫 번째 공백을 찾았습니다. 위치: 5
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
struct Person {
std::string name;
int age;
};
int main() {
std::vector<Person> people = {
{"Alice", 20},
{"Bob", 25},
{"Charlie", 30},
{"David", 35},
{"Eve", 40}
};
// 30세 이상인 사람 찾기
auto it1 = std::find_if(people.begin(), people.end(),
[](const Person& p) { return p.age >= 30; });
if (it1 != people.end()) {
std::cout << "30세 이상인 첫 번째 사람을 찾았습니다: "
<< it1->name << " (" << it1->age << "세)" << std::endl;
} else {
std::cout << "30세 이상인 사람을 찾지 못했습니다." << std::endl;
}
// 이름이 'B'로 시작하는 사람 찾기
auto it2 = std::find_if(people.begin(), people.end(),
[](const Person& p) { return p.name[0] == 'B'; });
if (it2 != people.end()) {
std::cout << "이름이 'B'로 시작하는 첫 번째 사람을 찾았습니다: "
<< it2->name << std::endl;
} else {
std::cout << "이름이 'B'로 시작하는 사람을 찾지 못했습니다." << std::endl;
}
return 0;
}
실행 결과:
30세 이상인 첫 번째 사람을 찾았습니다: Charlie (30세) 이름이 'B'로 시작하는 첫 번째 사람을 찾았습니다: Bob
| 함수 | 설명 |
|---|---|
| find_if(first, last, pred) | 주어진 범위에서 조건을 만족하는 첫 번째 요소를 찾음 |