Compare smaller vector to bigger to check if it differs at the end of smaller

  • A+
Category:Languages

We have two vectors of size that depends on runtime and need to check if they are equal - differ elements only after the end of smaller size vector. I used std::equal but the issue is that I need to find first which vector is of smaller size which leads to extra line of code :

#include <vector> #include <iostream>  int main() {   std::vector<int> a(1000, 3);   std::vector<int> a1(100, 3);    if(a.size() > a1.size())   {     if(std::equal(a1.begin(), a1.end(), a.begin()))     {       std::cout << "Same a gt a1" << std::endl;     }   }    if(a1.size() > a.size())   {     if(std::equal(a.begin(), a.end(), a1.begin()))     {       std::cout << "Same a1 gt a" << std::endl;     }   }    if(a1.size() == a.size())   {     if(std::equal(a.begin(), a.end(), a1.begin()))     {        std::cout << "Same a = a1" << std::endl;     }   } } 

Can the code to compare two vectors or differ only at the end of smaller vector be improved?

 


You only need one call of std::equal if you calculate the smaller size beforehand. I would refactor the code like this:

#include <vector> #include <iostream> #include <algorithm>  int main() {     std::vector<int> a(1000, 3);     std::vector<int> a1(100, 3);      if (std::equal(a1.begin(), a1.begin() + std::min(a.size(), a1.size()), a.begin()))      {         std::cout << "Same" << std::endl;     }     return 0; } 

If you need to preserve the second information about which vector is bigger, you could achieve it like this, for instance:

std::cout << "Same " << ((a.size() == a1.size())? "a = a1" : ((a.size() > a1.size())? "a gt a1" : "a1 gt a")) << std::endl; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: