【发布时间】:2011-08-15 20:21:12
【问题描述】:
可以使用 STL 二进制搜索算法(binary_search、upper_bound、lower_bound)在基指针向量中搜索派生对象,如下所示。由于 Base 是抽象的(受保护的构造函数),因此必须为搜索函数实例化一个 Derived 对象,这有点难看。
我想在给定时间以上的第一个 Derived 向量中搜索。我可以在不随意选择和实例化我的许多继承类之一的情况下做到这一点吗?
#include <algorithm>
#include <vector>
#include <stdio.h>
using namespace std;
class Base {
protected:
Base(double t, int d) : data(d), time(t) {}
public:
double time;
int data;
virtual void print() {
printf("Base: data = %d, time = %.1f\n",data,time);
}
};
class Derived : public Base {
public:
Derived(double t, int d) : Base(t,d) {}
virtual void print() {
printf("Derived: data=%d, time=%.1f\n",data,time);
}
};
struct BaseTimeComp {
bool operator()(Base* a, Base* b) { return a->time < b->time; }
};
int main()
{
vector<Base*> v;
for(int i=0; i<5; i++) { v.push_back(new Derived(i+0.4,i)); }
Base* pLow = *(lower_bound(v.begin(),v.end(),
new Derived(3.5,0), //NOT "new Base(3.5,0)"
BaseTimeComp()));
printf("lower bound for time=3.5:\n");
pLow->print();
}
程序打印: 时间=3.5 的下限: 推导:数据=4,时间=4.4
【问题讨论】:
标签: c++ stl abstract binary-search