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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…