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. eg:
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?
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 */ });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.