Lets say i Have a class like this
class Person
{
private:
int id;
string name ,lastname;
vector<Person> likedperson;
public:
//getter setters
}
how to check likedperson has a certain id like
Person user;
if(user.likedperson.contains(34))
//do stuff
else
//do stuff
You want to use std::find_if
that uses a UnaryPredicate, something like:
if (std::find_if(std::begin(likedperson), std::end(likedperson),
[](const Person& p) -> bool { return p.id == 34; }) != std::end(likedperson)) {
Unlike some languages, C++ mostly separates the algorithms that operate on containers (things that store data) from the containers themselves.
There's a standard algorithm to find an element, if it exists, in any container: std::find
. (See http://en.cppreference.com/w/cpp/algorithm/find for more details.)
You want something like
if (std::find(likedperson.begin(), likedperson.end(), 34) != likedperson.end())
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.