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?
A vector quantity has two characteristics, a magnitude and a direction. When comparing two vector quantities of the same type, you have to compare both the magnitude and the direction. On this slide we show three examples in which two vectors are being compared. Vectors are usually denoted on figures by an arrow.
If you're comparing the pointers themselves then you can just use operator== on the whole vector (of vectors). What it does is first checks if the sizes of the two vectors are equal. If they are, it subsequently compares each element using operator== .
Explanation: Once the vector is full i.e. number of elements in the vector becomes equal to the capacity of the vector then vector doubles its capacity i.e. if previous capacity was 2 then new capacity becomes 2 * 2 = 4 or 2 + 2 = 4.
C++ Vector Library - resize() Function The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector.
Since C++14, you can use std::mismatch
and check the pair of iterators returned against the end of each range:
auto it = std::mismatch(a.begin(), a.end(), a1.begin(), a1.end());
if (it.first == a.end() || it.second == a1.end()) {
// Equality
}
You also get to know where the elements start to differ, and if they don't, at which point the bigger vector is bigger (the start of the subrange you don't want to compare).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With