O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required