algorithm_mismatch
algorithm_mismatch (첫 불일치 찾기)
std::mismatch는 두 대상 범위에서 서로 일치하지 않는 첫 번째 요소 쌍을 찾아 두 반복자를 돌려줘요. 두 컨테이너를 비교할 때 처음으로 달라지는 위치가 필요할 때 써요.
출처: cppreference
본문
std::mismatch는 두 대상 범위 [first1, last1)과 [first2, last2)에서 서로 일치하지 않는 첫 요소 쌍을 가리키는 반복자 쌍을 돌려줘요. last2 매개변수가 없는 오버로드에서는 last2를 std::next(first2, std::distance(first1, last1))로 간주해요. <algorithm> 헤더에 정의되어 있어요.
template< class InputIt1, class InputIt2 >
std::pair<InputIt1, InputIt2>
mismatch( InputIt1 first1, InputIt1 last1,
InputIt2 first2 );
template< class InputIt1, class InputIt2, class BinaryPred >
std::pair<InputIt1, InputIt2>
mismatch( InputIt1 first1, InputIt1 last1,
InputIt2 first2, BinaryPred p );
- 1번 오버로드 — 요소를
operator==로 비교해요. - 2번 오버로드 — 요소를 이진 술어
p로 비교해요.
반환값 (Return value)
각각 첫 번째와 두 번째 범위에서 불일치 요소를 가리키는 반복자 쌍이에요. 첫 번째 범위의 모든 요소가 일치하면 first1 == last1이 아닌 경우 쌍은 (last1, 대응 반복자)를 돌려줘요.
복잡도 (Complexity)
최소 std::distance(first1, last1)번 이하의 비교(또는 p 적용)가 필요해요.
예제 (Example)
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v1{1, 2, 3, 4, 5};
std::vector<int> v2{1, 2, 9, 4, 5};
auto [it1, it2] = std::mismatch(v1.begin(), v1.end(), v2.begin());
if (it1 != v1.end())
std::cout << "First mismatch at index " << std::distance(v1.begin(), it1)
<< ": " << *it1 << " vs " << *it2 << '\n';
}
출력:
First mismatch at index 2: 3 vs 9