C++ 通过多个标准搜索元素?
下面的代码创建订单向量:C++ 通过多个标准搜索元素?,c++,data-structures,C++,Data Structures,下面的代码创建订单向量: #include <vector> struct Order { int uniqueId; double price; int time; }; using V = std::vector<Order>; int main() { V v { {1, 3.0, 5}, {2, 5.0, 7}, {3, 2.0, 1}}; return 0; } #包括 结构顺序 { 国际唯一性; 双
#include <vector>
struct Order
{
int uniqueId;
double price;
int time;
};
using V = std::vector<Order>;
int main()
{
V v { {1, 3.0, 5}, {2, 5.0, 7}, {3, 2.0, 1}};
return 0;
}
#包括
结构顺序
{
国际唯一性;
双倍价格;
整数时间;
};
使用V=std::vector;
int main()
{
V{1,3.0,5},{2,5.0,7},{3,2.0,1};
返回0;
}
我应该创建什么额外的数据结构,以便能够通过给定的time
和price
找到一个最小std::tie(order.price,order.time)
满足标准order.time>=time&&order.price>=price
,复杂性为O(log2 N)
如果我们发现多个订单,我们会选择具有最小
uniqueId的订单,该订单保证是唯一的。我认为二叉搜索树将非常适合该任务,因为访问、搜索、插入、删除等操作意味着日志(n)
的时间复杂性,其中n
是数据的大小
<>在C++中,可以使用<代码> STD::SET容器,它内部构造为默认的“代码< >”二叉搜索树operator@ThomasSablik两次搜索的结果是不同的元素,是吗?@Thomas在价格>=2.5
和时间最低但大于1
的项目中,价格较低的项目确实具有uniqueId=1
。您对我的代码时间复杂性的批评更为集中,我创建了一个集合
太多了,如果有办法修改同一集合
中的比较函数,那将非常正确,因为我不需要为每次比较创建一个全新的集合。@Thomas我使用time=1,price=2.5
作为我的示例的阈值,因此结果不同。@Thomas使用constrainttime=1,price=2.5
,您输入的三个新订单中的任何一个都可以。唯一ID最低的实际订单实际上是第1项。我可以在minuniqueId
上添加另一个检查,但我更愿意解决构建多个集的问题。如果只有初始的集合
,而不涉及其他副本构造,那么此解决方案确实会实现复杂性log(n)
。这是一个很好的解决方案。我认为使用带有适当比较函数的std::set
比使用排序的std::vector
要好。注释不用于扩展讨论;这段对话已经结束。
#include <iostream>
#include <set>
#include <tuple>
using std::cout; using std::endl;
using std::set; using std::lower_bound;
using std::make_tuple;
struct Order
{
int uniqueId;
double price;
int time;
};
struct Compare {
bool operator() (const Order& lhs, const Order& rhs) const
{auto l_tuple = make_tuple(lhs.price, lhs.time, lhs.uniqueId);
auto r_tuple = make_tuple(rhs.price, rhs.time, rhs.uniqueId);
return l_tuple < r_tuple;}
};
using S = set<Order, Compare>;
int main()
{
// define set ordered, respectively, by prices, time, uniqueId
S my_set({ {1, 3.0, 5}, {2, 5.0, 7}, {3, 2.0, 1} });
Order K = {0, 2.5, 1}; // example of threshold for price and time
auto next_K = my_set.lower_bound(K); // iterator
cout << "Minimal order with price at least = " << K.price << " and time at least = "
<< K.time << " has ID: " << next_K->uniqueId << endl;
return 0;
}