Solved

# Sort pointers in container

Posted on 2002-07-01
178 Views
I have a container with pointers that I'm trying to sort.

How do you sort a container of pointers?

class XObject
{
public:
int xyz;
};

list<XObject*> ptrListOfXObject;

How do I sort ptrListOfXObject in order of xyz data member?
0
Question by:ROWANBRIGHTON
1 Comment

LVL 30

Accepted Solution

Axter earned 270 total points
Here is some example code.

#include <list>
#include <iostream>

class myObject{
public:
myObject(){m_Val = 0;}
int getVal() const //Constant here
{
return m_Val;
}
void setVal(int pVal){m_Val = pVal;}
private:
int m_Val;
};

template<>
struct std::greater<myObject*>
{
public:
virtual bool operator()(const myObject*& lhs, const myObject*& rhs) const
{
return lhs->getVal() > rhs->getVal();
}
};

class ProcessOrder
{
public:
void SomeFunction();
private:

typedef std::list<myObject *> MYLIST;
MYLIST myList;
};

void ProcessOrder::SomeFunction()
{
const Qty = 4;
myObject My_myObject[Qty];
int SomeNum[Qty] = {3, 8, 7, 2};
for (int i = 0;i < Qty;++i)
{
myList.push_back(&My_myObject[i]);
}

myList.sort(std::greater<myObject*>());

for (MYLIST::iterator x = myList.begin();x != myList.end();++x)
{
std::cout << (*x)->getVal() << std::endl;
}
}

int main(int argc, char* argv[])
{
ProcessOrder MyProcessOrder;
MyProcessOrder.SomeFunction();
system("pause");
return 0;
}
0

## Featured Post

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…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.