开发者

priority_queues in C++

开发者 https://www.devze.com 2023-01-26 21:50 出处:网络
I\'m a bit of a noob to iterators. I\'m trying to create a priority_queue, sorted by vector length. (I.e., I want to pop off the longest vectors in order.)

I'm a bit of a noob to iterators. I'm trying to create a priority_queue, sorted by vector length. (I.e., I want to pop off the longest vectors in order.)

This is the resource that I've been using:

http://www.cplusplus.com/reference/stl/priority_queue/priority_queue/

I tried this code, and it seems to do what I want:

// testing to make sure that a priority queue will always give me the longest vector
priority_queue< vector<int> > q;

vector<int> f;
f.push_back(1);

vector<int> g;
g.push_back(19);
g.push_back(80);

vector<int> y;
y.push_back(62);
y.push_back(10);
y.push_back(11);

q.push(f);
q.push(g);
q.push(y);

vector<int> out = q.top();

for (unsigned int i = 0; i < out.size(); i++) {
    cout << out[i] << endl;
}

My questions: 1. Will this always give me the longest vector? This seems to be the case. 2. 开发者_运维技巧If not, what else should I do? The iterator syntax on the reference page is like... o_O

Thanks!!


No, the code doesn't do what you expect. It compares the vectors lexicographically rather than by length. To compare by length use a custom comparator:

struct LengthCompare {
    bool operator() (const vector<int>& a, const vector<int>& b) {
        return a.size() < b.size();
    }
};

priority_queue<vector<int>, vector<vector<int> >, LengthCompare> q;

Also note that your queue stores copies of the vectors, which might be not so efficient because it may copy them when it builds the heap. Store (smart) pointers instead.


priority_queues in C++ use a Comparison object to determine what is the greatest element. By default, this is the < (less-than) operator over the objects held in the priority_queue - so you need to know what < means over vectors. This page http://www.cplusplus.com/reference/stl/vector/operators/ has some information about that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号