본문 바로가기
언리얼_엔진_게임개발_공부/C++

[C++] <algorithm> search() / <string> find()

by jaboy 2024. 12. 30.

search(start1, end1, start2, end2)

[start1, end1)의 범위에서 [start2, end2) 시퀀스를 검색해 찾은 경우, 찾은 시퀀스의 첫번째 원소를 가리키는 반복자를 반환한다.

찾지 못한 경우 v2.end() 를 반환한다.

예) v1 = [1, 2, 3, 4, 5] 에서 v2 = [3, 4] 를 검색하면 반복자는 v1의 3을 가리키고 있다.

int main() {
    vector<int> v1 = { 1, 2, 3, 4, 5 };
    vector<int> v2 = { 3, 4 };

    vector<int>::iterator it = search(v1.begin(), v1.end(), v2.begin(), v2.end());
    for (; it != v1.end(); it++)
        cout << *it << endl;

    return 0;
}

출력값: 3 / 4 / 5

 

참고: https://cplusplus.com/reference/algorithm/search/

 

https://cplusplus.com/reference/algorithm/search/

function template <algorithm> std::search equality (1)template ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2);predicate (2)template ForwardIterator1 search (ForwardIterator1 first1

cplusplus.com

 

string1.find(string2)

string1 에서 string2 의 char 시퀀스를 검색해 찾은 경우, 찾은 시퀀스의 첫번째 char 를 가리키는 위치를 반환한다.

찾지 못한 경우 npos (i.e. null position) 를 반환한다.

예) string1 = "Hello" 에서 string2 = "el"를 검색하면 string1 내 'e'의 위치를 반환한다.

int main() {
    string string1 = "Hello";
    string string2 = "el";
    string::size_type n = string1.find(string2);
    cout << string1.substr(n);

    return 0;
}

출력값: ello

 

참고: https://en.cppreference.com/w/cpp/string/basic_string/find

 

std::basic_string<CharT,Traits,Allocator>::find - cppreference.com

size_type find( const basic_string& str, size_type pos = 0 ) const; (1) (noexcept since C++11) (constexpr since C++20) size_type find( const CharT* s, size_type pos, size_type count ) const; (2) (constexpr since C++20) size_type find( const CharT* s, size_

en.cppreference.com