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

前端 未结 5 395
一向
一向 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<Car> const & cars = get_a_set_of_cars();
    std::set<Car>::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.

    0 讨论(0)
  • 2020-12-03 16:29

    You may try overriding operator<(const T& a, const T& b) to impose an order on those attributes, so std::set:find(const T& x) will return the first no less than x.

    Ej:

    bool operator<(const Car& a, const Car& b)
    {
        return a.color<b.color || (a.color==b.color && a.doors<b.doors) || (a.color==b.color && a.doors==b.doors && a.top_speed<b.top_speed);
    }
    
    std::set<Car> cars;
    Car x;
    cars.find(x);
    
    0 讨论(0)
  • 2020-12-03 16:37

    This depends on the implementation of T. Let's stick with your example of a class Car. Suppose that class looks something like this:

    class Car {
    public:
        Car(std::string color, unsigned int number_of_doors,
            unsigned int top_speed);
        // getters for all these attributes
        // implementation of operator< as required for std::set
    };
    

    The operator< should order instances of Car based on all attributes in order to make searching for all attributes possible. Otherwise you will get incorrect results.

    So basically, you can construct an instance of car using just these attributes. In that case, you can use std::set::find and supply a temporary instance of Car with the attributes you are looking for:

    car_set.find(Car("green", 4, 120));
    

    If you want to search for an instance of Car specifying only a subset of its attributes, like all green cars, you can use std::find_if with a custom predicate:

    struct find_by_color {
        find_by_color(const std::string & color) : color(color) {}
        bool operator()(const Car & car) {
            return car.color == color;
        }
    private:
        std::string color;
    };
    
    // in your code
    
    std::set<Car>::iterator result = std::find_if(cars.begin(), cars.end(), 
                                                  find_by_color("green"));
    if(result != cars.end()) {
        // we found something
    }
    else {
        // no match
    }
    

    Note that the second solution has linear complexity, because it cannot rely on any ordering that may or may not exists for the predicate you use. The first solution however has logarithmic complexity, as it can benefit from the order of an std::set.

    If, as suggested by @Betas comment on your question, you want to compose the predicates at runtime, you would have to write some helper-classes to compose different predicates.

    0 讨论(0)
  • 2020-12-03 16:39

    When faced to such problems, I usually maintain:

    • A std::deque or std::vector of cars
    • For each property you want to look up against, a std::multiset of pointers to cars, sorted by the property value.

    I carefully hide those containers inside a class which allows me to insert cars.

    The querying interface may vary, but usually, you make advantage of multiset::equal_range, std::sort and std::set_intersection.

    If you want a red Volvo whatever... car, you

    1. extract by equal_range all the red cars, giving you an iterator pair
    2. extract by equal_range all the Volvo cars, giving you an iterator pair
    3. ...
    4. Sort all these ranges by a common predicate, say by pointer address
    5. Apply repeatedly set_intersection into a std::deque.

    Another way is to store the cars into a deque, enumerate them and pick the one which satisfies all your properties, using std::find. This may have worse complexity however (it depends on how many red cars you have for isntance)

    0 讨论(0)
  • 2020-12-03 16:40

    The std::set allows you to provide your own comparison function, as in

    template < class Key, class Compare = less<Key>,
           class Allocator = allocator<Key> > class set; 
    

    Only compare the values you care about and it will act as if objects with those values are =. Note that you will probably need a multiset for this.

    This would be the way to do it if you really care about logn performance.

    0 讨论(0)
提交回复
热议问题