如何在std :: set中查找具有特定字段值的对象?

ale*_*xfr 7 c++ stl set find

我调用一个返回std::set<T> const&where T类型的方法.我想要实现的是检查集合是否包含T具有特定字段值的类型的对象,用于自动测试中的断言.应该对多个对象进行此检查.

下面是一个简单的例子:让类型TCar这样一个例子set,包含了一些汽车.现在我想找到一辆具有特定颜色特定门数的汽车以及该套装中的特定最高速度.如果发现车的第一个断言是真的,并与其他字段值的下一辆车应该可以找到.

我不允许改变执行T.使用Boost就行了.

你会怎么做?

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对你的问题发表评论,你想在运行时编写谓词,你就必须编写一些辅助类来编写不同的谓词.