简体   繁体   English

按成员数据搜索向量中的结构项

[英]Search for a struct item in a vector by member data

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.我对 C++ 很陌生,我正在尝试找到一种方法来搜索具有特定成员数据的结构的结构向量。

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;
};

and a vector like this:和这样的向量:

vector<Friend> friends;

Then the vector is filled with friends.然后向量中充满了朋友。

Let's say I want to search for a friend with a certain ID, and cout the details.假设我想搜索具有特定 ID 的朋友,并查询详细信息。 Or delete the certain struct from the vector.或者从向量中删除某个结构体。 Is there a simple way to do this?有没有一种简单的方法可以做到这一点?

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:这可以通过std::find_if和搜索谓词来完成,如果您有 C++11(或 C++0x)可用,则可以将其表示为 lambda 函数:

auto pred = [](const Friend & item) {
    return item.ID == 42;
};
std::find_if(std::begin(friends), std::end(friends), pred) != std::end(friends);

To use an ID given as a variable, you have to capture it in the lambda expression (within the [...] ):要使用作为变量给出的 ID,您必须在 lambda 表达式中(在[...]捕获它:

auto pred = [id](const Friend & item) {
    return item.ID == id;
};
std::find_if(std::begin(friends), std::end(friends), pred) != std::end(friends);

If you don't have C++11 available, you have to define the predicate as a functor (function object).如果没有可用的 C++11,则必须将谓词定义为函子(函数对象)。 Remy Lebeau's answer uses this approach. Remy Lebeau 的回答使用了这种方法。

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).要删除与谓词定义的条件匹配的元素,请使用remove_if而不是find_if (其余语法相同)。

For more algorithms, see the STL <algorithm> reference .有关更多算法,请参阅STL <algorithm>参考

Use std::find_if() .使用std::find_if() @leemes and @AndyProwl showed you how to use it in a C++11 compiler. @leemes 和 @AndyProwl 向您展示了如何在 C++11 编译器中使用它。 But if you are not using a C++11 compiler, then you can use it like this instead, which defines a functor comparing the ID of a given item with a previously specified ID in its constructor:但是如果你没有使用 C++11 编译器,那么你可以像这样使用它,它定义了一个函子,将给定项的 ID 与其构造函数中先前指定的 ID 进行比较:

class MatchesID
{
    std::string _ID;

public:
    MatchesID(const std::string &ID) : _ID(ID) {}

    bool operator()(const Friend &item) const
    {
        return item.ID == _ID;
    }
};

std::find_if(vector.begin(), vector.end(), MatchesID("TheIDHere")) != vector.end();

If you have other classes in your project which use IDs, you can make this functor templated:如果您的项目中有其他使用 ID 的类,您可以将此函子模板化:

template<typename IDType>
class MatchesID
{
    IDType _ID;

public:
    MatchesID(const IDType &ID) : _ID(ID) {}

    template<class ItemType>
    bool operator()(const ItemType &item) const
    {
        return item.ID == _ID;
    }
};

std::find_if(vector.begin(), vector.end(), MatchesID<std::string>("TheIDHere")) != vector.end();

You can use std::find_if in combination with functors (if you are working with C++98) or lambdas (if you are using C++11, which I will assume):您可以将std::find_if与函子(如果您使用的是 C++98)或 lambdas(如果您使用的是 C++11,我假设)结合使用:

using namespace std;
int ID = 3; // Let's say...
auto it = find_if(begin(vector), end(vector), [=] (Friend const& f) { 
    return (f.ID == ID); 
    });
bool found = (it != end(vector));

If you want to find an element in STL container, use std::find or std::find_if algorithms With C++03, you need to overload operator== for std::find如果要在 STL 容器中查找元素,请使用std::findstd::find_if算法 在 C++03 中,需要为 std::find 重载 operator==

bool operator==(const Friend& lhs, const Friend& rhs)
{
  return lhs.ID == rhs.ID;
}

if (std::find(friends.begin(), friends.end(), item) != friends.end())
{
   // find your friend
}

OR C++11 with lambda:或 C++11 与 lambda:

std::find_if(friends.begin(), friends.end(),  [](Friend& f){ return f.ID == "1"; } );

If you want to remove a certain element, use std::remove_if如果要删除某个元素,请使用std::remove_if

std::remove_if(friends.begin(), friends.end(), 
      [](Friend& f){ return f.ID == "1"; });

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM