简体   繁体   English

C ++检查类对象是否包含某个元素

[英]C++ check whether a classes object contains a certain element

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 如何检查喜欢的人是否有特定的ID

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: 您想使用使用std::find_if ,例如:

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. 与某些语言不同,C ++大多将对容器(存储数据的事物)进行操作的算法与容器本身分开。

There's a standard algorithm to find an element, if it exists, in any container: std::find . 有一种标准算法可以在任何容器中找到元素(如果存在): std::find (See http://en.cppreference.com/w/cpp/algorithm/find for more details.) (有关更多详细信息,请参见http://en.cppreference.com/w/cpp/algorithm/find 。)

You want something like 你想要类似的东西

if (std::find(likedperson.begin(), likedperson.end(), 34) != likedperson.end())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在C ++中检查集合是否包含某个范围内的元素 - how to check whether a set has element(s) in certain range in C++ C ++检查构造函数是否包含给定类型的参数 - C++ check whether constructor contains a parameter of given type 有没有一种方法可以检查字符串是否在C ++中包含Unicode字符 - Is there a way to check whether a string contains unicode characters in C++ 检查两个元素在C ++中是否具有公共元素 - Check whether two elements have a common element in C++ (C ++)用于检查对象是否在vector / array / list /…中的模板? - (C++) Template to check whether an object is in a vector/array/list/…? 如何检查类数组的元素是否为空? [c ++] - How do I check if an element of an array of classes is empty? [c++] C ++:确定变量是否不包含数据 - C++: Determining whether a variable contains no data 如何检查字符串是否包含一定数量的字符并包含(或不包含)某些字符? C ++ - How to check if a string is certain amount of characters and contains (or doesn't contain) certain characters? C++ 在 C++ 中打印某个数字是否回文 - Print whether a certain number is Palindromic or not in C++ 将向量中指向元素的指针设置为null,然后检查指针是否为null(C ++) - Set pointer to element in vector to null, then check whether pointer is null (C++)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM