mismatch() Function in C++

This C++ program demonstrates the mismatch algorithm. The mismatch algorithm used takes three arguments – the first two arguments are iterators to beginning and end of first container and the third argument is iterator to beginning of second container. The mismatch algorithm returns pair of iterator to the first mismatch of container elements.

Here is the source code of the C++ program demonstrates the mismatch algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate mismatch() algorithm
  3.  */
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <vector>
  7.  
  8. void fun(int val)
  9. {
  10.     std::cout << val << " ";
  11. }
  12.  
  13. // Print vector routine
  14. void print(std::vector<int> v)
  15. {
  16.     for_each(v.begin(), v.end(), fun);
  17.     std::cout << std::endl;
  18. }
  19.  
  20. int main()
  21. {
  22.     std::vector <int> k(5), l(5);
  23.     typedef std::vector <int>::iterator i;
  24.  
  25.     for (int i = 0; i < k.size(); i++)
  26.     {
  27.         k[i] = i;
  28.         if(i < 3)
  29.             l[i] = i;
  30.     }
  31.     std::pair <i, i> p = mismatch(k.begin(), k.end(), l.begin());
  32.     std::cout << "Vector k : ";
  33.     print(k);
  34.     std::cout << "Vector l : ";
  35.     print(l);
  36.     std::cout << "Mismatched indexes : " << (p.first - k.begin())
  37.               << " " << (p.second - l.begin()) << std::endl;
  38.     std::cout << "Mismatched values  : " << *(p.first)
  39.               << " " << *(p.second) << std::endl;
  40. }

$ a.out
Vector k : 0 1 2 3 4 
Vector l : 0 1 2 0 0 
Mismatched indexes : 3 3
Mismatched values  : 3 0

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.