Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

how to sort a queue?

Posted on 2006-11-13
11
Medium Priority
?
303 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
[X]
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
  • 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
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.

730 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