converting/constructing vector of tuples into heap

白昼怎懂夜的黑 提交于 2020-07-07 10:33:58

问题


- Construction

i constructed a vector of tuples vector<tuple<int,int,int>> x. For sake of simplicity, lets assume it is constructed it this way.

vector<tuple<int,int,int>> x;
for (int ii=0; ii < 10; ii++){
    for (int jj=0; jj < 10; jj++){
        currpeak[0] = ii + rand() % 10;
        currpeak[1] = jj + rand() % 10;
        currpeak[2] = rand() % 100;
        x.emplace_back(currpeak[0], currpeak[1], currpeak[2]);
    }
}

Now i want to get the n largest tuples, according to the 3rd element, and append them to another variable vector<tuple<int,int,int>> y. Lets assume n=10.

- Sorting

Currently i am doing it this way : reverse sorting them, then choosing the first n elements.

// Sort them by 3rd element
bool sortbythird_desc(const tuple<int,int,int>& a, 
            const tuple<int,int,int>& b){
    return (get<2>(a) > get<2>(b)); 
}
sort(x.begin(), x.end(), sortbythird_desc);

// Extract the top 10 elements from x and put into y
vector<tuple<int,int,int>> y;
for(int jdx =0; jdx<10; jdx++){
    int curr_peak0=get<0>(x[jdx]);
    int curr_peak1=get<1>(x[jdx]);
    int curr_peak2=get<2>(x[jdx]);
    y.emplace_back(curr_peak0, curr_peak1, curr_peak2);
}

However this is O(nlogn) operations due to the sorting.

- Failed heap attempt

If i can convert x to a heap, or even construct it as a heap from the beginning : O(n) operations. pop_heap : O(log n) times. In total it would take only O(n + log n) = O(n) operations. However the following fails

// Convert x to a heap
bool Comp(const tuple<int,int,int>& a){
    return get<2>(a); 
}
make_heap(x.begin(), x.end(), Comp);

Error

Severity    Code    Description Project File    Line    Suppression State
Error   C2197   'bool (__cdecl *)(const std::tuple<int,int,int> &)': too many arguments for call    Shash   C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xutility    1481    

How do i modify my code to convert x to a heap, or even to construct 1 in the first place ?


回答1:


The easiest way is to pass a struct with the () operator. For example

struct Comp { 
    bool operator()(const tuple<int,int,int>& a, 
            const tuple<int,int,int>& b){
           return (get<2>(a) > get<2>(b)); 
    }
};

And pass this to make_heap



来源:https://stackoverflow.com/questions/62754378/converting-constructing-vector-of-tuples-into-heap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!