Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 通过多个标准搜索元素?_C++_Data Structures - Fatal编程技术网

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使用constraint
time=1,price=2.5
,您输入的三个新订单中的任何一个都可以。唯一ID最低的实际订单实际上是第1项。我可以在min
uniqueId
上添加另一个检查,但我更愿意解决构建多个
集的问题。如果只有初始的
集合
,而不涉及其他副本构造,那么此解决方案确实会实现复杂性
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;
}