How to find an object with specific field values in a std::set?

前端 未结 5 428
一向
一向 2020-12-03 16:09

I call a method which returns std::set const& where T is a class type. What I\'m trying to achieve is to check whether the set contain

5条回答
  •  眼角桃花
    2020-12-03 16:19

    You'll want std::find_if, with a predicate function object that checks the properties you're interested in. It might look something like this:

    struct FindCar {
        FindCar(Colour colour, int doors, double top_speed) :
            colour(colour), doors(doors), top_speed(top_speed) {}
    
        bool operator()(Car const & car) const {
            return car.colour == colour
                && car.doors == doors
                && car.top_speed == top_speed;
        }
    
        Colour colour;
        int doors;
        double top_speed;
    };
    
    std::set const & cars = get_a_set_of_cars();
    std::set::const_iterator my_car =
        std::find_if(cars.begin(), cars.end(), FindCar(Red, 5, 113));
    

    In C++0x, you could replace the "FindCar" class with a lambda to make the code a bit shorter.

提交回复
热议问题