开发者

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

I call a method which returns std::set<T> const& where T i开发者_JAVA百科s a class type. What I'm trying to achieve is to check whether the set contains an object of type T with specific field values for an assertion in a automated test. This check should be done for multiple objects.

Here is a simple example: Let the type T be Car so an example set contains a bunch of cars. Now I want to find a car with a specific color and a specific number of doors and a specific top speed in that set. If that car is found the first assertion is true and the next car with other field values should be found.

I'm not allowed to change the implementation of T. The usage of Boost would be OK.

How would you do that?


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.


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.


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)


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜