在载体中成员数据搜索结构项目 [英] Search for a struct item in a vector by member data
问题描述
我很新的C ++和我试图找到一种方法来搜索结构的载体具有一定的会员数据的结构。
I'm very new to c++ and I'm trying to find a way to search a vector of structs for a struct with a certain member data.
我知道这将与简单的工种,在载体
I know this would work with simple types in the vector
std::find(vector.begin(), vector.end(), item) != vector.end()
不过,可以说我有一个这样的结构:
But lets say I have a struct like this:
struct Friend
{
string name;
string number;
string ID;
};
和这样的载体:
vector<Friend> friends;
然后,向量填充有朋友。
Then the vector is filled with friends.
比方说,我要寻找具有一定的ID的朋友,和COUT的细节。或删除某些结构的载体。有一个简单的方法来做到这一点?
Let's say I want to search for a friend with a certain ID, and cout the details. Or delete the certain struct from the vector. Is there a simple way to do this?
推荐答案
这可以用完成的std :: find_if
和搜索predicate,它可以是pssed作为一个lambda函数,如果你有C ++ 11 EX $ P $(或的C ++ 0x)可供选择:
This can be done with std::find_if
and a search predicate, which can be expressed as a lambda function if you have C++11 (or C++0x) available:
auto pred = [](const Friend & item) {
return item.ID == 42;
};
std::find_if(std::begin(friends), std::end(friends), pred) != std::end(friends);
要使用给出一个变量的ID,你要的捕捉的它在拉姆达EX pression(在 [...]
):
To use an ID given as a variable, you have to capture it in the lambda expression (within the [...]
):
auto pred = [id](const Friend & item) {
return item.ID == id;
};
std::find_if(std::begin(friends), std::end(friends), pred) != std::end(friends);
如果你没有C ++ 11可用,你必须定义predicate为仿函数(函数对象)。 雷米勒博的回答使用了这种方法。
If you don't have C++11 available, you have to define the predicate as a functor (function object). Remy Lebeau's answer uses this approach.
要由predicate定义删除元素相匹配的标准,使用的remove_if
而不是 find_if
(的语法的其余部分是相同的)。
To remove elements matching the criteria as defined by the predicate, use remove_if
instead of find_if
(the rest of the syntax is the same).
有关更多的算法,请参见 STL的&LT;算法&GT;
引用。
For more algorithms, see the STL <algorithm>
reference.
这篇关于在载体中成员数据搜索结构项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!