7.4. Comparing Ranges

Problem

You have two ranges, and you need to compare them for equality or you need to see which one comes first based on some ordering on the elements.

Solution

Depending on what kind of comparison you want to do, use one of the standard algorithms equal, lexicographical_compare, or mismatch, defined in <algorithm>. Example 7-4 shows several of them in action.

Example 7-4. Different kinds of comparisons

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include "utils.h"

using namespace std;
using namespace utils;

int main() {

   vector<string> vec1, vec2;

   vec1.push_back("Charles");
   vec1.push_back("in");
   vec1.push_back("Charge");

   vec2.push_back("Charles");
   vec2.push_back("in");
   vec2.push_back("charge");  // Note the small "c"

   if (equal(vec1.begin(), vec1.end(), vec2.begin())) {
      cout << "The two ranges are equal!" << endl;
   } else {
      cout << "The two ranges are NOT equal!" << endl;
   }

   string s1 = "abcde";
   string s2 = "abcdf";
   string s3 = "abc";

   cout << boolalpha  // Show bools as "true" or "false"
        << lexicographical_compare(s1.begin(), s1.end(),
                                   s1.begin(), s1.end()) << endl;
   cout << lexicographical_compare(s1.begin(), s1.end(),
                                   s2.begin(), s2.end()) << endl;
   cout << lexicographical_compare(s2.begin(), s2.end(),
                                   s1.begin(), s1.end()) << endl;
   cout << lexicographical_compare(s1.begin(), s1.end(),
                                   s3.begin(), s3.end()) << endl;
   cout << lexicographical_compare(s3.begin(), s3.end(), s1.begin(), s1.end()) << endl; pair<string::iterator, string::iterator> ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.