![](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2Fx61G1%2FbtqMTf4xU6D%2FSEUB0JwCMpi6K91v9K0Qk0%2Fimg.png)
C++ Vector 값 탐색 find - 존재 유무 확인
Notepad96
·2020. 11. 12. 21:55
1. find, find_if
vector에서 특정 데이터가 존재하는지 확인하고 싶다.
그렇다면 algorithm 라이브러리의 find를 사용할 수 있다.
find는 반복자를 인자로 갖으면서 배열, vector, deque 처럼 일련의 데이터 구조에서 특정 데이터가 존재하는 확인할 수 있다.
또한, find_if를 사용하면 특정 조건에 일치하는 데이터를 탐색할 수 있다.
2. 코 드
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
bool isOdd(int n) {
return n % 2 == 1;
}
int main() {
vector<int> v;
v.push_back(46);
v.push_back(67);
v.push_back(184);
v.push_back(4);
v.push_back(17);
v.push_back(53);
cout << "현재 vector : ";
for (int i : v) cout << i << " ";
cout << "\n==============================\n";
int num = 4;
auto it = find(v.begin(), v.end(), num);
if (it == v.end()) {
cout << num << "은 찾을 수 없습니다.\n";
}
else {
cout << num << "는 존재하며 인덱스는 " << it - v.begin() << " 입니다.\n";
}
cout << "\n==============================\n";
cout << "홀수(Odd)들 \n";
auto it2 = find_if(v.begin() , v.end(), isOdd);
while (it2 != v.end()) {
cout << *it2 << "\n";
it2 = find_if(it2+1, v.end(), isOdd);
}
return 0;
}
![](https://blog.kakaocdn.net/dn/W7smF/btqM2G03JsV/AU1fXYZzAD1AIoTKk2Nzw0/img.png)
3. 참 조
find - C++ Reference
123456789 template InputIterator find (InputIterator first, InputIterator last, const T& val) { while (first!=last) { if (*first==val) return first; ++first; } return last; }
www.cplusplus.com
find_if - C++ Reference
123456789 template InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred) { while (first!=last) { if (pred(*first)) return first; ++first; } return last; }
www.cplusplus.com
'C++ > STL' 카테고리의 다른 글
C++ 일련하는 원소 찾기 Search (0) | 2020.11.13 |
---|---|
C++ 원소 개수 구하기 Count (0) | 2020.11.13 |
C++ Vector 최대값, 최소값, 인덱스 구하기 (0) | 2020.11.12 |
C++ 조합(Combination) - next_permutation (1) | 2020.11.12 |
C++ 순열(Permutation) - next_permutation (0) | 2020.11.11 |