Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

how to sort a queue?

Posted on 2006-11-13
11
Medium Priority
?
308 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
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!

 

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 200 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

879 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