简体   繁体   English

如何排序std :: list <..>

[英]How to sort std::list<..>

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). 我在m_list对象中有x个项,这些项必须由新对象中的PhaseIndex变量排序(曾经的类型)。 In the end i need x lists of the CDataTransferElement Elements where each list has only Elements with the same PhaseIndex. 最后,我需要X个CDataTransferElement元素列表,其中每个列表仅包含具有相同PhaseIndex的元素。

How do i do that at best? 我最好怎么办?

regards camelord 问候骆驼

Loop through your list adding each CDataTransferElement to a new list stored in a map. 遍历您的列表,将每个CDataTransferElement添加到存储在地图中的新列表。

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 );
}

Use the header 使用标题

It provides std::sort(std::iterator begin,std::iterator end) 它提供了std :: sort(std :: iterator begin,std :: iterator end)

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

You will probably need to use a custom comparator. 您可能需要使用自定义比较器。 See for example sort std::list case sensitive elements . 参见例如sort std :: list区分大小写的元素

If you want to use std::sort, you can overload the operator < in your class. 如果要使用std :: sort,则可以在类中重载运算符<。 I think using vector rather than list is much better if you want random access 我认为如果要随机访问,使用向量而不是列表会更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM