Be careful trying to use the operator==() for comparing Vectors.
I read multiple answers on this topic on various forums, but nobody seems to mention this only works as in the example below, for native types:
std::vector<int> v1{ 1, 3, 5, 7 }; // create a vector with 4 elements
std::vector<int> v2{ 1, 3, 5, 7 }; // let's make this vector the same
// now compare:
if (v1 == v2) {
std::cout << "SUCCESS!!!" << std::endl;
}
Yes, the above code will work! (I just tried it. :)
However, the following code will not work without quite a bit of effort:
class Foo {
public:
int m_num = { 7 };
Foo(int n=0) : m_num(n) {}
};
// Create our comparison vectors filled with Objects of type Foo:
std::vector<Foo> foo1{ 1, 3, 5, 7 };
std::vector<Foo> foo2{ 1, 3, 5, 7 };
// This will not compile:
if (foo1 == foo2) {
std::cout << "SUCCESS!!!" << std::endl;
}
After some aggravation, I did find a relatively painless way to make the above comparison, however:
// First create a predicate function to perform the equivalency test:
bool match(Foo& f1, Foo& f2)
{
return f1.m_num == f2.m_num;
}
// Then use std::equal() like so:
if (std::equal(foo1.begin(), foo1.end(), foo2.begin(), foo2.end(),match))
{
std::cout << "### VECTORS MATCH!!! ###" << std::endl;
}
Hope this helps save someone the same aggravation I just went through trying to figure out how to make this work.
operator==
for the class would be the normal approach, whether you were comparing oneFoo
to another, or comparing avector
of them. And in any case, this doesn't address the OP's question, which was about comparing part of a vector to part of another. – Archaean