I am trying to solve a simple solution for comparing 2 vectors in this post in C++. Let us use STL vectors and std:: equal function to compare.There are different ways the comparison can be achieved.1. Using the == operatorExample :vector<int> first = {2,4,6,8,10};vector<int> second = {2,4,6,8,10};Comparing them can be done using ‘==’ operator as follows:if (first == second){ std::cout << “The vectors are same” << std::endl;}The problems with == area. It cannot use custom comparatorsb. Cannot compare sub-vector groups2. std:: equal can be used to comparefor equality:bool equal (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2);for predicate:bool equal (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate pred);Equality can be used to compare sub vectors:Example:Comparing all elements can be done by usingbool isEqual = std::equal(first.begin(),first.end(),second.begin());Comparing the subset of elements the following can be done.vector<int> a = {1,2,3,4,5,6};
vector<int> b = {4,5,6};
bool isEqual = std::equal( b.begin(),b.end(), a.begin()+2);
if(isEqual)
{
cout<<"The vectors are equal"<<endl;
}We can use custom comparators. Let’s see how we can do it.vector<string> first ={"this", "is", "a", "practise", "of","custom", "comparators"};
vector<string> second ={"THIS", "IS", "A", "PRACTISE", "OF","CUSTOM", "COMPARATORS"};
std::function< bool (const string &, const string & )> comparator = [](const string &left, const string &right)
{
return std::equal(left.begin(),left.end(),right.begin(),[](const char &l,const char &r){ return ::toupper(l)==::toupper(r))});
}
bool isEqual = std::equal(first.begin(),first.end(),second.begin(),comparator);
if(isEqual)
cout<<"The strings are same"<<endl;
else
cout<<"The strings are not same"<<endl;
Discover more from A Streak of Communication
Subscribe to get the latest posts sent to your email.