Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

how to sort a queue?

Posted on 2006-11-13
11
280 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
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to programmatically differentiate between C and Java 10 204
Header of docx file 17 113
max float value 3 51
C++ Code Issue 4 22
Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
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.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

790 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