Reputation: 1155
I have a vector v containing objects of type structure say A. Now I need to find the iterator for a particular object stored in this vector. e.g:
struct a
{
};
vector<a> v;
struct temp; //initialized
Now if I will use
find(v.begin(),v.end(), temp);
then compiler generates error saying no match for operator '=='
.
Any workaround for getting an iterator corresponding to an object in a vector?
Upvotes: 0
Views: 119
Reputation: 227390
You have to provide either a bool operator==(const a& lhs, const a& rhs)
equality operator for your class, or pass a comparison functor to std::find_if
:
struct FindHelper
{
FindHelper(const a& elem) : elem_(elem) {}
bool operator()(const a& obj) const
{
// implement equality logic here using elem_ and obj
}
const a& elem_;
};
vector<a> v;
a temp;
auto it = std::find_if(v.begin(), v.end(), FindHelper(temp));
Alternatively, in c++11 you can use a lambda function instead of the functor.
auto it = std::find_if(v.begin(), v.end(),
[&temp](const a& elem) { /* implement logic here */ });
Upvotes: 2