Hey guys,
Sorry for the long title; it's not as longwinded as you may think.
On several occasions in my project, I need to sort elements (indeces) based on their linked values. Those values are stored in an array. This means the comparison looks like this:
bool operator()(int i, int j) { return someArray[i] > someArray[j]; }
Because this form returns often but someArray may differ, I wrapped this in a template class:
1 2 3 4 5 6
|
template<class T>
struct sorter {
std::vector<T>& data;
sorter(std::vector<T>& __d) : data(__d) {}
bool operator()(int i, int j) const { return data[i] > data[j]; }
};
|
(Conceptually, only sorting by '>' makes sense, so ambiguous name is not such a problem.)
Now, I want to use this in a different way: I want to select the K indeces with the lowest value from someArray attached to it. My idea was to build a priority_queue, push the first K elements and then compare all the next elements to PQ.top(), as such:
1 2 3 4 5 6 7 8
|
INDEX t(0);
for (; t < someLimit; ++t) {
pq.push(t);
if (pq.size() == K) break;
}
for (; t < someLimit; ++t) {
if (someArray[t] < someArray[pq.top()]) { pq.pop(); pq.push(t); }
}
|
My problem, however, is the definition / initialization of the priority_queue object. My first idea was simply
std::priority_queue<INDEX> pq(sorter<VALUE>(someArray));
, but calling any function on pq provides the error "expression must have class type" (?) when hovering over pq.
My second guess,
std::priority_queue<INDEX, std::vector<INDEX>, sorter<VALUE>(someArray)> pq;
, provides the error 'expected a ')'' when hovering over someArray.
What is the correct way to initialize this data structure?