0

I have a C++ problem. I'm working with CodeBlocks, and I'm declaring: #include < queue > to use a priority_queue like that:

priority_queue<pair<int,int>,vector<int>,Lower> p;

where Lower is defined:

struct Lower{
   bool operator<<(priority_queue<pair<int,int>,vector<int>,Menor> p1, priority_queue<pair<int,int>,vector<int>,Menor> p2){ 
     return p1.second<p2.second;
   }
}

And, when I'm trying to iterate over p, declaring an iterator:

priority_queue<pair<int,int>,vector<int>,Menor>::iterator it;

It returns this error:

error: 'iterator' is not a member of 'std::priority_queue<std::pair<int, int> >'

I hope you can help me! Thanks.

Theolodis
  • 4,977
  • 3
  • 34
  • 53
user3529582
  • 165
  • 2
  • 11
  • If you're hoping to get a sequence sorted on priority you can squelch that idea right now. A priority queue from the standard library is little more than a container adapter wrapped around a random access container (i.e. a deque, a vector) that is used for storage of a min-**heap**. and the resulting iteration would *not* be priority sorted. – WhozCraig May 15 '14 at 15:31

1 Answers1

1

You can not iterate over a std::priority_queue as this functionality is not provided by its interface.

If you need to be able to iterate over the elements then maybe std::priority_queue is not the right choice of container.

If you want a sorted container that you can iterate over, then perhaps you could use a std::set instead?

std::set<std::pair<int, int>> s;
s.emplace(20, 2);
s.emplace(10, 2);

// Iterate over pairs in sorted order.
for (auto& pair : s) {
    /* ... */
}

Or if you need contiguous data allocation then maybe use a std::vector together with std::sort?

std::vector<std::pair<int, int>> v;
v.emplace_back(20, 2);
v.emplace_back(10, 2);

std::sort(std::begin(v), std::end(v)); // Sort elements.

// Iterate over pairs...
for (auto& pair : s) {
    /* ... */
}
Felix Glas
  • 15,065
  • 7
  • 53
  • 82