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

时间:2013-01-08 23:36:54

标签: c++ algorithm std

我对c ++很新,我正试图找到一种方法来搜索具有特定成员数据的结构的结构向量。

我知道这适用于矢量中的简单类型

std::find(vector.begin(), vector.end(), item) != vector.end()

但是我可以说我有这样的结构:

struct Friend
{
  string name;
  string number;
  string ID;
};

和这样的矢量:

vector<Friend> friends;

然后向量充满了朋友。

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

4 个答案:

答案 0 :(得分:22)

这可以使用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);

要使用作为变量提供的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);

如果您没有可用的C ++ 11,则必须将谓词定义为函子(函数对象)。 Remy Lebeau's answer使用此方法。

要删除与谓词定义的条件匹配的元素,请使用remove_if而不是find_if(其余语法相同)。

有关更多算法,请参阅the STL <algorithm> reference

答案 1 :(得分:12)

使用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();

如果您的项目中有其他使用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();

答案 2 :(得分:4)

您可以将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));

答案 3 :(得分:2)

如果要在STL容器中查找元素,请使用std::findstd::find_if算法 使用C ++ 03,您需要重载operator == for std :: find

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:

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

如果要删除某个元素,请使用std::remove_if

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