Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page