[C++] find()함수
2024. 1. 22. 01:26
728x90
SMALL
📌 1. <algorithm
> find()
#include<algorithm>
find(start, end, value);
- start부터 last 전까지 원소들 중 value와 일치하는 첫 번째 원소의 iterator를 리턴함
- 범위 내에 value값이 없다면 end 리턴
//ex)
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
vector<int> numbers = {1, 2, 3, 4,5};
int target = 3;
auto it = find(numbers.begin(), numbers.end(), target);
if(it!=numbers.end()){
cout<<"원하는 값 찾음 : "<<*it<<endl;
}
else{
cout<<"원하는 값 못찾음"<<endl;
}
return 0;
}
📌 2. <string
> find()
- 문장.find(패턴)
- 패턴을 문장 안에서 찾으면 인덱스를 반환함
- 찾지 못한다면 string::npos 값을 반환함
#include<iostream>
#include<string>
using namespace std;
int main(){
string str = "Hello, World!";
string pattern = "World";
size_t found = str.find(pattern);
if(found != string::npos){
cout<<"패턴 발견. 인덱스: "<<found<<endl;
}
else{
cout<<"패턴 발견 실패."<<endl;
return 0;
}
반응형
⚡ 두 find()의 차이
1) 적용 대상
- <
string
>의 find() :문자열
에서 패턴을 검색 - <
algorithm
>의 find() : 일반적인 시퀀스(컨테이너, 배열 등)에서 값 검색
2) 사용 방법
- <
string
>의 find() : std::string 객체의 멤버함수로 사용- ex)
str.find(pattern)
- ex)
- <
algorithm
>의 find() : 알고리즘 함수로 사용- ex) std::find(container.begin(), container.end(), value)
3) 반환값
- <
string
>의 find()- 검색된 패턴의
첫 번째 문자의 인덱스
를 반환함 - 발견하지 못했다면
std::string::npos
반환함
- 검색된 패턴의
- <
algorithm
>의 find() : 일반적인 시퀀스(컨테이너, 배열 등)에서 값 검색- 검색된 값을 가리키는 반복자를 반환
- 발견하지 못했다면 컨테이너의 끝(
end()
)을 가리키는 반복자 반환
728x90
LIST
'Language > C++' 카테고리의 다른 글
[C++] class VS 구조체 (0) | 2024.01.26 |
---|---|
[C++] <vector> (0) | 2024.01.26 |
[C++] priority queue (우선순위 큐) 란? (0) | 2024.01.26 |
[C++] <algorithm> (1) | 2024.01.22 |
[C++] cpp의 기본 내용 정리 (1) | 2024.01.22 |