8 Key Standard Library Algorithms

Comparing Only Part of Two Ranges

Can I use std::ranges::equal() to compare only a part of two ranges?

Abstract art representing computer programming

Yes, you can use std::ranges::equal() to compare only a part of two ranges by specifying subranges.

This can be done using iterator pairs or views to define the portions of the ranges you want to compare.

Here's an example that demonstrates comparing parts of two vectors:

#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>

int main() {
  std::vector<int> vec1{1, 2, 3, 4, 5};
  std::vector<int> vec2{10, 2, 3, 40, 50};

  auto subrange1 = std::ranges::subrange(
    vec1.begin() + 1, vec1.begin() + 3);  

  auto subrange2 = std::ranges::subrange(
    vec2.begin() + 1, vec2.begin() + 3);  

  if (std::ranges::equal(subrange1, subrange2)) {
    std::cout << "Subranges are equal\n";
  } else {
    std::cout << "Subranges are not equal\n";
  }
}
Subranges are equal

In this example, subrange1 and subrange2 represent parts of vec1 and vec2, respectively.

Specifically, they represent the elements from the second to the fourth element (inclusive).

The std::ranges::equal() function compares these subranges and prints the result.

Alternatively, you can use views to achieve the same result:

#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>

int main() {
  std::vector<int> vec1{1, 2, 3, 4, 5};
  std::vector<int> vec2{10, 2, 3, 40, 50};

  auto view1 = vec1
    | std::views::drop(1)  
    | std::views::take(2);      

  auto view2 = vec2
    | std::views::drop(1)  
    | std::views::take(2);      

  if (std::ranges::equal(view1, view2)) {
    std::cout << "Views are equal\n";
  } else {
    std::cout << "Views are not equal\n";
  }
}
Views are equal

In this example, std::views::drop(1) and std::views::take(3) are used to create views of the specified subranges.

The std::ranges::equal() function then compares these views.

Using subranges or views allows you to compare only specific parts of your ranges, making std::ranges::equal() a flexible tool for various comparison needs.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved