这取决于T 的实现。让我们继续使用 Car 类的示例。假设该类看起来像这样:
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
};
operator< 应根据所有属性 对Car 的实例进行排序,以便搜索所有属性。否则你会得到错误的结果。
所以基本上,您可以只使用这些属性来构造汽车的实例。在这种情况下,您可以使用 std::set::find 并提供带有您要查找的属性的 Car 临时实例:
car_set.find(Car("green", 4, 120));
如果您想搜索Car 的实例,仅指定其属性的一个子集,就像所有绿色汽车一样,您可以将std::find_if 与自定义谓词一起使用:
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
}
请注意,第二种解决方案具有线性复杂性,因为它不能依赖于您使用的谓词可能存在或不存在的任何排序。然而,第一个解决方案具有对数复杂性,因为它可以从 std::set 的顺序中受益。
如果按照@Betas 对您的问题的评论所建议的那样,您想在运行时组合谓词,则必须编写一些辅助类来组合不同的谓词。