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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14225932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:08:23  来源:igfitidea点击:

Search for a struct item in a vector by member data

c++algorithmstd

提问by Christoffer

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. Or delete the certain struct from the vector. Is there a simple way to do this?

假设我想搜索具有特定 ID 的朋友,并查询详细信息。或者从向量中删除某个结构体。有没有一种简单的方法可以做到这一点?

回答by leemes

This can be done with std::find_ifand 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 captureit 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). Remy Lebeau's answeruses this approach.

如果没有可用的 C++11,则必须将谓词定义为函子(函数对象)。Remy Lebeau 的回答使用了这种方法。

To remove elements matching the criteria as defined by the predicate, use remove_ifinstead 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>参考

回答by Remy Lebeau

Use std::find_if(). @leemes and @AndyProwl showed you how to use it in a C++11 compiler. 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:

使用std::find_if(). @leemes 和 @AndyProwl 向您展示了如何在 C++11 编译器中使用它。但是如果你没有使用 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();

回答by Andy Prowl

You can use std::find_ifin 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));

回答by billz

If you want to find an element in STL container, use std::findor std::find_ifalgorithms 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"; });