gpt4 book ai didi

c++ - 将元组 vector 构造成堆

转载 作者:行者123 更新时间:2023-12-02 09:53:01 24 4
gpt4 key购买 nike

here,我能够将元组的 vector 转换为堆。
但是,我想更进一步地从头开始构造元组,而无需转换 vector 。
我以前如何构造 vector 的方法如下:

vector<tuple<int,int,int>> x;
for (int ii=0; ii < 10; ii++){
for (int jj=0; jj < 10; jj++){
y[0] = ii + rand() % 10;
y[1] = jj + rand() % 10;
y[2] = rand() % 100;
x.emplace_back(y[0], y[1], y[2]);
}
}
我如何尝试从头开始构建堆
struct Comp { 
bool operator()(const tuple<int,int,int>& a,
const tuple<int,int,int>& b){
return (get<2>(a) < get<2>(b));
}
};

vector<tuple<int,int,int>> x;

for (int ii=0; ii < 10; ii++){
for (int jj=0; jj < 10; jj++){
y[0] = ii + rand() % 10;
y[1] = jj + rand() % 10;
y[2] = rand() % 100;
x.emplace_back(y[0], y[1], y[2]);
push_heap(x.begin(), x.end(), Comp()); // using push_heap
}
}
push_heap()行上的错误:
Severity    Code    Description Project File    Line    Suppression State
Error C2228 left of '.begin' must have class/struct/union
Error (active) E0153 expression must have class type
Error (active) E0153 expression must have class type
Error C2780 'void std::push_heap(_RanIt,_RanIt,_Pr)': expects 3 arguments - 2 provided
Error C2672 'push_heap': no matching overloaded function found

最佳答案

您正在使用x作为堆和元组的名称。再加上operator[]并不是访问元组字段的方法。另外,您尝试多次创建堆
我想你的意思是这样的

for (int ii=0; ii < 10; ii++){
for (int jj=0; jj < 10; jj++){
tuple<int,int,int> y;
get<0>(y) = ii + rand() % 10;
get<1>(y) = jj + rand() % 10;
get<2>(y) = rand() % 100;
x.emplace_back(y);
}
}
push_heap(x.begin(), x.end(), Comp()); // using push_heap
甚至更简单
for (int ii=0; ii < 10; ii++){
for (int jj=0; jj < 10; jj++){
x.emplace_back(ii + rand() % 10, jj + rand() % 10, rand() % 100);
}
}
push_heap(x.begin(), x.end(), Comp()); // using push_heap

关于c++ - 将元组 vector 构造成堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62756886/

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