Reputation: 2742
I'm having some trouble keeping objects in a vector, and I think I need to do something with the operators.
std::vector<Foo> vec;
Foo a = Foo();
vec.push_back(a);
...
if(std::find(vec.begin(), vec.end(), a) < vec.end()) {
// Found
} else {
// Not found
}
Foo needs operator== to compile, I do this
bool Foo::operator==(const Foo& rhs) {
return this == &rhs;
}
But from what I understand, vec.push_back
, is going to make a copy of the Foo object, so my == will return false.
Hence, whenever I get to the searching, it is never found.
What's the right thing to do here? I'm hoping to avoid switching to a vector of pointers.
Upvotes: 1
Views: 79
Reputation: 2016
There is really nothing you can do, std::vector<> (or rather most standard containers) makes copies on insertions. If equality of two Foo objects is really defined by their addresses being equal the only thing you can do is to store pointers in the std::vector<>. If you want to store pointers in the std::vector<> I'd recommend storing smart-pointers instead like std::shared_ptr<>, std::unique_ptr<>.
If Foo's is too heavy to copy you can make Foo Move-only in C++11 or you can make it move only in C++03 using boost::containers::vector and boost::move.
Probably it is just easier to change the operator==() to compare the member variables instead.
Upvotes: 1
Reputation: 14386
Change the implementation of Foo::operator==
to compare the member variables of Foo for equality instead of checking identity. For example:
bool Foo::operator==(const Foo& rhs) const {
return get_a() == rhs.get_a()
&& get_b() == rhs.get_b(); // and so on
}
Note that this can also be a const
function since it should not modify any member variables and should be usable on const
instances of Foo.
Upvotes: 2
Reputation: 7946
Your operator==
implies that identity is defined by its location in memory, but the fact that you are appending values to a vector and hoping for equality says that identity is NOT defined by location.
If for some reason you don't have an identity definition based on any other members, you can add a unique identifier to your Foo objects, can compare that identifier in your code:
bool operator==(const Foo &rhs)
{
return this->m_id == rhs.m_id;
}
Upvotes: 1