Bjö*_*lex 16
这取决于实施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
};
Run Code Online (Sandbox Code Playgroud)
该operator<应当责令实例Car基于所有属性,以使搜索所有属性可能的.否则您将得到不正确的结果.
所以基本上,您可以仅使用这些属性构建汽车实例.在这种情况下,您可以使用std::set::find并提供具有Car您要查找的属性的临时实例:
car_set.find(Car("green", 4, 120));
Run Code Online (Sandbox Code Playgroud)
如果要搜索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
}
Run Code Online (Sandbox Code Playgroud)
请注意,第二种解决方案具有线性复杂性,因为它不能依赖于您使用的谓词可能存在或不存在的任何排序.然而,第一种解决方案具有对数复杂性,因为它可以从a的顺序中受益std::set.
如果@Betas对你的问题发表评论,你想在运行时编写谓词,你就必须编写一些辅助类来编写不同的谓词.