Solved

how to sort a queue?

Posted on 2006-11-13
11
282 Views
Last Modified: 2012-05-05
i have a queue that consists of a number of user defined structs:

struct people
{
     int age;
     int height;
     .
     .
     .   // etc
};

i defined the queue as follows:

queue <people> group_q;

there are a certain amount of person instances of the people (people person1, person2, ..... etc) and some of these people have been added to the group_q queue.... now im wanting to pop certain elements out of the group_q based on certain attributes of the instances (ex.  person1.age for example)

how do i sort a queue so that the highest/lowest age is at the head/front of the queue, so that when i pop the group_q, ill get the oldest/youngest person currently in the people_q queue?

thanks
0
Comment
Question by:jadedpuppy
  • 6
  • 4
11 Comments
 
LVL 7

Expert Comment

by:UrosVidojevic
ID: 17934177
Hi,

It is very unefficient to use queue class for that purpose, you'll have to pop all elements out of the queue, sort them with some n log n algorithm, and push them back in queue.

Better, more efficient and elegant solution is to use priority_queue class which sorts queue elements automaticaly by the criteria you give. The only thing you should do is to define < operator which will help queue to decide how to sort elements.

This is an example:

#include <queue>
using namespace std;

struct people {
        int age;
        int height;
        ....
};

// Supose you want to sort people by age, so that the highest age is at a head of the queue:

bool operator< (const people& p1, const people& p2) {
        return p1.age < p2.age;
}

int main() {
        priority_queue <people> group_q;
        // after you have pushed elements in with function push(), you can access "head-elenent" with the function group_q.pop(), and delete it with function group_q.pop().
}

I hope, it was helpful.
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 17934320
Or, if you mainly intend to pull them off in various orders based on various criteria, then a queue<> is the wrong kind of container.  For instance, a list<> with a sort() member might be a better choice.  If you need to retain the original order, then add a struct member to record the order in which they were added.  Then sorting by that sequence number gives you the ordering you need.
0
 

Author Comment

by:jadedpuppy
ID: 17934860
yeah priority_queue looks like something that would make my life a little easier

but when i enter:
priority_queue <people> group_q;

i get a crazy error at compile, if i comment the above line out, it compiles fine..... any ideas?

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:jadedpuppy
ID: 17934876
/usr/lib/gcc/i386-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_function.h: In member function `bool std::                                       less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = process]':
/usr/lib/gcc/i386-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_heap.h:279:   instantiated from `void std:                                       :__adjust_heap(_RandomAccessIterator, _Distance, _Distance, _Tp, _Compare) [with _RandomAccessIterator = __gnu_cxx::__                                       normal_iterator<process*, std::vector<process, std::allocator<process> > >, _Distance = int, _Tp = process, _Compare =                                        std::less<process>]'
/usr/lib/gcc/i386-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_heap.h:404:   instantiated from `void std:                                       :make_heap(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_i                                       terator<process*, std::vector<process, std::allocator<process> > >, _Compare = std::less<process>]'
/usr/lib/gcc/i386-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_queue.h:369:   instantiated from `std::pri                                       ority_queue<_Tp, _Sequence, _Compare>::priority_queue(const _Compare&, const _Sequence&) [with _Tp = process, _Sequenc                                       e = std::vector<process, std::allocator<process> >, _Compare = std::less<process>]'
project1_1.cpp:270:   instantiated from here
/usr/lib/gcc/i386-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_function.h:227: error: no match for 'opera                                       tor<' in '__x < __y'

thats the error i get when i leave the above line in
0
 
LVL 7

Expert Comment

by:UrosVidojevic
ID: 17934933
#include <queue>
using namespace std;

struct people {
        int age;
        int height;
};


bool operator< (const people& p1, const people& p2) {
        return p1.age < p2.age;
}

int main() {
        priority_queue <people> group_q;
}

I compiled this code under MS VisualStudio and Linux gcc c++ and it doesn't reports any errors or warnings.

Try to compile it from command line with:

g++ MyProgram.C -o MyProgram
0
 

Author Comment

by:jadedpuppy
ID: 17934957
yeah ok that worked (your last bit of code).... but its the exact same thing?  it should compile in my other file as well
0
 

Author Comment

by:jadedpuppy
ID: 17934988
ok i figured it ou, i was declaring the bool operator in my main().... stupid mistake
0
 

Author Comment

by:jadedpuppy
ID: 17935016
now for one last question (hopefully, lol)..... how do you then use the < operator to sort the Q?

also, i was looking at the priority_queue definition.... and the pop function removes the largest element from the Q from the top position.... what if i wanted to remove the smallest element?  is there a way to do this?
0
 
LVL 7

Accepted Solution

by:
UrosVidojevic earned 50 total points
ID: 17935065
1.) You don't use operator < to sort, queue uses it automaticaly, so you do not need to worry about that. It will sort it alone, and it needs operator < because it uses it to sort elements. So, just push elements, queue itself will take care of sorting by using defined operator.

2.) If you want to have access to the smallest element, your queue must be sorted from smallest to largest element, to do that, just change deffinition of operator < :

bool operator< (const people& p1, const people& p2) {
        return p1.age > p2.age;
}
0
 

Author Comment

by:jadedpuppy
ID: 17935081
awesome thanks.... my mistake was i was canged both '<' symbols, and was getting an error.... didnt think to just change the 2nd '<' symbol.... thanks again
0
 
LVL 7

Expert Comment

by:UrosVidojevic
ID: 17935101
nice, keep coding... :-)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Least Squares Curve Fitting 4 114
Safe conversion? 4 75
VS2015 Redefinition errors 4 87
need help ...get stuck at middle of coding ...need to submit by Sunday C++ 1 43
When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question