Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

c++ - 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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.

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).

For more algorithms, see the STL <algorithm> reference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...