【问题标题】:constructing vector of tuples into heap将元组向量构造成堆
【发布时间】:2020-07-06 13:13:44
【问题描述】:

here,我能够将元组向量转换为堆。 但是我想更进一步地从头开始构造元组,从而消除了转换向量的需要。

我之前构造向量的方式如下:

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

【问题讨论】:

标签: c++ vector tuples heap


【解决方案1】:

您使用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

【讨论】:

  • 我对 push_heap() 的功能有误解吗?我的印象是它是逐元素(每个元组)的操作,因此我将它包含在 for 循环中。
  • 其实你是对的,我的粗心在x.emplace_back(x[0], x[1], x[2]);应该是x.emplace_back(y[0], y[1], y[2]);而不是
猜你喜欢
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 2019-08-04
相关资源
最近更新 更多