Tuesday, December 19, 2017

C++98: std::mismatch()

The template function std::mismatch() returns the pair of iterators where two sequences mismatch. Here is an example:

#define _SCL_SECURE_NO_WARNINGS 1 // Turn off Microsoft Error/Warning

#include <algorithm>
#include <iostream>

int main()
{
  int sequence1[8] = {1, 3, 2, 4, 5, 7, 6, 9};
  int sequence2[8] = {1, 3, 2, 4, 5, 7, 6, 9};
  int sequence3[8] = {1, 3, 2, 4, 5, 7, 6, 1};

  std::pair mismatchIterators;

  mismatchIterators = std::mismatch(&sequence1[0], 
                                    &sequence1[8],
                                    &sequence2[0]);  

  std::cout << mismatchIterators.first -&sequence1[0] << " "; // 8 (Index)
  std::cout << mismatchIterators.second-&sequence2[0] << " "; // 8 (Index)

  mismatchIterators = std::mismatch(&sequence1[0],
                                    &sequence1[8],
                                    &sequence3[0]);
  std::cout << *mismatchIterators.first  << " "; // 9 (Value)
  std::cout << *mismatchIterators.second << " "; // 1 (Value)

  std::cout << std::endl;
  return 0;
}
// Output: 8 8 9 1
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, p. 158-60.

No comments:

Post a Comment