Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard way to compare two ranges in C++?

Tags:

c++

iterator

stl

By range I mean a pair of iterators. In pseudo C++:

std::vector<int> v1 = { 1, 2, 3, 4, 5 }; std::vector<int> v2 = { 2, 3, 4 }; if( std::compare_range( v1.begin() + 1, v1.end() - 1, v2.begin(), v2.end() ) {     std::cout << "Alright\n"; } 

compare_range being of course the function I'm looking for.

Disclaimer: This is a pretty trivial function to write, I know. But like all programmers, I try to be lazy ;-)

like image 738
Pedro d'Aquino Avatar asked Mar 23 '11 12:03

Pedro d'Aquino


2 Answers

std::equal is the function template you are looking for.

if (std::equal(v1.begin() + 1, v1.end() - 1, v2.begin()) {     std::cout << "Alright\n"; } 

Note that std::equal only takes three arguments, not four.

like image 165
fredoverflow Avatar answered Sep 18 '22 17:09

fredoverflow


Use std::equal - it supports ranges as well.

like image 38
Alexander Gessler Avatar answered Sep 21 '22 17:09

Alexander Gessler