Search for a struct item in a vector by member data

后端 未结 4 1556
后悔当初
后悔当初 2020-11-29 03:36

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

4条回答
  •  没有蜡笔的小新
    2020-11-29 04:18

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

提交回复
热议问题