gpt4 book ai didi

c++ - 我如何 (C++ STL) binary_search 抽象类?

转载 作者:行者123 更新时间:2023-11-30 01:29:29 25 4
gpt4 key购买 nike

可以使用 STL 二进制搜索算法(binary_search、upper_bound、lower_bound)来搜索派生对象的 Base 指针 vector ,如下所示。由于 Base 是抽象的( protected 构造函数),因此必须为搜索函数实例化一个 Derived 对象,这有点难看。

我想在给定时间以上搜索第一个 Derived 的 vector 。我可以在不任意选择和实例化我的许多继承类之一的情况下做到这一点吗?

#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

最佳答案

比较的目标不必与容器的内容类型相同,它只需要是您可以与容器比较的东西即可:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
vector<int> v;

v.push_back(1);
v.push_back(2);
v.push_back(3);

int i = *(lower_bound(v.begin(), v.end(), 1.5)); // <<< NOTE: floating point "value"

cout << i << endl;
}

您认为必须制作某种Base 的假设是错误的。只要您的显式(或隐式)比较运算符知道要做什么,您就可以定义适合您比较的 BaseKey

下面的评论也是错误的,正如这个更复杂的例子所展示的:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

struct A {
int x;
A(int _x) :x(_x) { }

bool operator < (double d) { return x < d; }
};

int main()
{
vector<A> v;

v.push_back(A(1));
v.push_back(A(2));
v.push_back(A(3));

int i = (lower_bound(v.begin(), v.end(), 1.5))->x;

cout << i << endl;
}

您还可以显式使用比较类型(这有助于解决操作顺序问题,例如您可能会在 upper_bound 中发现):

class CompareADouble {
public:
bool operator () (const double d, A& a) { return d < a.x; }
};

int main()
{
vector<A> v;

v.push_back(A(1));
v.push_back(A(2));
v.push_back(A(3));

int i = (upper_bound(v.begin(), v.end(), 1.5, CompareADouble()))->x;

cout << i << endl;
}

binary_search 示例提供了与多态性的比较:

class CompareADouble {
public:
bool operator () (const double d, A& a) { return d < a.x; }
bool operator () (A& a, const double d) { return a.x < d; }
};

...

bool exists = binary_search(v.begin(), v.end(), 1.5, CompareADouble());
cout << exists << endl; // false

exists = binary_search(v.begin(), v.end(), 1.0, CompareADouble());
cout << exists << endl; // true because 1.0 < 1 == false && 1 < 1.0 == false

关于c++ - 我如何 (C++ STL) binary_search 抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5838287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com