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

前端 未结 5 449
一向
一向 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: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)

提交回复
热议问题