💡 퀵 접속: cpp.kr/find_if_not
C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 특정 조건을 만족하지 않는 첫 번째 요소를 찾습니다. 조건은 단항 술어 함수로 제공되며, 조건을 만족하지 않는 첫 번째 요소의 반복자를 반환합니다.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {2, 4, 6, 7, 8, 10};
// 홀수 찾기 (짝수가 아닌 수)
auto it1 = std::find_if_not(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_not(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;
}
실행 결과:
첫 번째 홀수를 찾았습니다: 7 5보다 작거나 같은 첫 번째 수를 찾았습니다: 2
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
std::string str = "Hello123";
// 숫자가 아닌 문자 찾기
auto it1 = std::find_if_not(str.begin(), str.end(),
[](char c) { return std::isdigit(c); });
if (it1 != str.end()) {
std::cout << "첫 번째 숫자가 아닌 문자를 찾았습니다: " << *it1 << std::endl;
} else {
std::cout << "숫자가 아닌 문자를 찾지 못했습니다." << std::endl;
}
// 대문자가 아닌 문자 찾기
auto it2 = std::find_if_not(str.begin(), str.end(),
[](char c) { return std::isupper(c); });
if (it2 != str.end()) {
std::cout << "첫 번째 대문자가 아닌 문자를 찾았습니다: " << *it2 << std::endl;
} else {
std::cout << "대문자가 아닌 문자를 찾지 못했습니다." << std::endl;
}
return 0;
}
실행 결과:
첫 번째 숫자가 아닌 문자를 찾았습니다: H 첫 번째 대문자가 아닌 문자를 찾았습니다: e
#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_not(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;
}
// 이름이 'A'로 시작하지 않는 사람 찾기
auto it2 = std::find_if_not(people.begin(), people.end(),
[](const Person& p) { return p.name[0] == 'A'; });
if (it2 != people.end()) {
std::cout << "이름이 'A'로 시작하지 않는 첫 번째 사람을 찾았습니다: "
<< it2->name << std::endl;
} else {
std::cout << "이름이 'A'로 시작하지 않는 사람을 찾지 못했습니다." << std::endl;
}
return 0;
}
실행 결과:
30세 미만인 첫 번째 사람을 찾았습니다: Alice (20세) 이름이 'A'로 시작하지 않는 첫 번째 사람을 찾았습니다: Bob
| 함수 | 설명 |
|---|---|
| find_if_not(first, last, pred) | 주어진 범위에서 조건을 만족하지 않는 첫 번째 요소를 찾음 |