tags:

views:

72

answers:

4

Hi,

i have a list of Elemtents of a custom type:

std::list<CDataTransferElement*> m_list;

The class is defined like this:

    class CDataTransferElement
{
public:
    CDataTransferElement(void);
    ~CDataTransferElement(void);

    CString Name;
    double PercentValue;
    double MOLValue;
    int PhaseIndex;

};

I have x Items in the m_list Object, that have to be sorted by the PhaseIndex Variable in a new Object (what type of ever). In the end i need x lists of the CDataTransferElement Elements where each list has only Elements with the same PhaseIndex.

How do i do that at best?

regards camelord

A: 

Use the header

It provides std::sort(std::iterator begin,std::iterator end)

http://www.cppreference.com/wiki/stl/algorithm/sort

Maz
That would sort the pointers, wouldn't it? :)
Nikolai N Fetissov
You can provide a custom comparison object. But I think what the OP really wants is to separate the list into several new lists, not sort it.
Michael Anderson
`std::sort` requires random access iterators, so it won't work with `std::list`. `std::list` provides its own `sort()` method.
Fred Larson
A: 

You will probably need to use a custom comparator. See for example http://stackoverflow.com/questions/2346714/sort-stdlist-case-sensitive-elements#2346721 .

Brian
+1  A: 

Loop through your list adding each CDataTransferElement to a new list stored in a map.

std::map<int,std::list<CDataTransferElement*> > m;
for( std::list<CDataTransferElement*>::iterator i=m_list.begin(); i!=m_list.end(); ++i)
{
  m[ (*it)->PhaseIndex ].append( (*it) );
}

You can then loop over the map to do whatever you like with the new separated lists.

for( std::map<int,std::list<CDataTransferElement*> >::iterator it = m.begin();
     it!=m.end();
     ++it )
{
  do_somthing_with_list( it->first, it->second );
}
Michael Anderson
thanks, thats what i looked for!
camelord
At least someone read the entire question.
Sean Farrell
A: 

If you want to use std::sort, you can overload the operator < in your class. I think using vector rather than list is much better if you want random access

Rambo