数据加载中……

利用STL中的sort对vector中指针元素的排序

本以为很简单的一个sort,却始终排不出来正确的顺序,让我有些纳闷,后来仔细一想,我只是对指针(地址)进行了排序,并没有对vector中的元素进行排序。

#include <algorithm>
#include 
<iostream>
#include 
<vector>

using namespace std;

class MyClass
{
public:
    MyClass(
void{}
    
~MyClass(void{}

    
int m_value;
}
;


bool cmp( const MyClass* p1,const MyClass* p2 )
{
    
return (*p1).m_value<(*p).m_value;
}


int _tmain(int argc, _TCHAR* argv[])
{
    vector
<MyClass*> m_pVector;

    MyClass
* a = new MyClass;
    a
->m_value = 12;
    m_pVector.push_back(a);

    a 
= new MyClass;
    a
->m_value = 25;
    m_pVector.push_back(a);

    a 
= new MyClass;
    a
->m_value = 8;
    m_pVector.push_back(a);

    sort(m_pVector.begin(),m_pVector.end(),cmp);

    
for (vector<MyClass*>::iterator it = m_pVector.begin(); it != m_pVector.end(); it++
        std::cout 
<< (*it)->m_value << std::endl;

    system(
"pause");

    
return 0;
}


上面就是简单的一个demo,对指针容器进行排序。

posted on 2011-04-25 12:37 Stone xin 阅读(3403) 评论(0)  编辑 收藏 引用 所属分类: STL&&BOOST


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理