将元组的向量构造成堆

constructing vector of tuples into heap

本文关键字:向量 元组      更新时间:2023-10-16

从这里,我能够将元组向量转换为堆。 但是,我想进一步追溯从头开始构建元组,而无需转换向量。

我之前如何构建向量如下:

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