I call a method which returns std::set<T> const& where T is 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 classCar. Suppose that class looks something like this:The
operator<should order instances ofCarbased 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::findand supply a temporary instance ofCarwith the attributes you are looking for:If you want to search for an instance of
Carspecifying only a subset of its attributes, like all green cars, you can usestd::find_ifwith a custom predicate: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.