-1

I am trying to find if an object's attribute is in the vector. For example, if I have a vector of Car objects and the Car object have attributes of license, direction, and time. And I want to find if direction 'N' is in the vector of Car object. And return true or false if the attribute is in the vector of Cars.

This is the function I have so far, but I want to use the stl find() method to search for the attribute:

bool isIn(std::vector<Car *> c, std::string check){
for (auto i = 0; i < c.size(); i++)
{
    if (c[i]->dir == check)
    {
        return true;
    }
}
return false;

}

The arguments that are passed in are the vector of Cars and the direction.

1 Answers1

1

In your situation std::find_if could be the solution

auto it = find_if(c.begin(), c.end(), [&check](const Car& obj) {return obj.getDir() == check;})
bogdan tudose
  • 1,064
  • 1
  • 9
  • 21
  • So I changed it up a bit: auto it = find_if(c.begin(), c.end(), [&check](const Car *obj) { return obj->dir == check; }); . What will it return? – Vyas Ramankulangara Feb 05 '19 at 19:22
  • most probably this will generate a compilation error. If you don't like passing by reference you can pass by value [&check](Car obj). This will return a object of type iterator, which you can then dereferentiate and get the actual Car object which match condition – bogdan tudose Feb 05 '19 at 19:43
  • I did pass by reference first it gave me an error: "no known conversion for argument 1 from 'Car*' to 'const Car&' " – Vyas Ramankulangara Feb 05 '19 at 19:53
  • I change the vector of Car * to vector of Car – Vyas Ramankulangara Feb 05 '19 at 20:07
  • Yes, that's correct as OznOg correctly stated in comments. However your proposal to give pointer as argument in lambda expression `[&check](const Car *obj) { return obj->dir` would definitely work in this case. Also, you should consider implementing getters for your memeber and made them private – bogdan tudose Feb 05 '19 at 20:14
  • The only problem I am facing is how to check if the Car's attribute direction is equal to check. – Vyas Ramankulangara Feb 05 '19 at 20:17
  • `return obj.getDir() == check;` this is the check you need. Expression will return `true`if getDir() is equal to check and `false` otherwise – bogdan tudose Feb 05 '19 at 20:18
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/187953/discussion-between-vyas-ramankulangara-and-bogdan-tudose). – Vyas Ramankulangara Feb 05 '19 at 20:19