2012-10-25 45 views
0

我有类,这个类包含一个数字。而且我有一个vector包含类的对象指针。我想根据它们的数量对这些对象进行排序。我怎样才能做到这一点? 感谢您的回答。包含对象的矢量的排序元素

#include <iostream> 
#include <vector> 
#include <algorithm> 
using namespace std; 

class Course 
{ 
public: 
    Course (int code, string const& name) : name(n), code(c) {} 
    int getCourseCode() const { return code; } 
    string const& getName() const { return name; } 

private: 
    string name; 
    int code; 
}; 

int main() 
{ 
    vector<Course*> cor; 
    vector<Course*>::iterator itcor; 

    cor.push_back(new Course(3,"first")); 
    cor.push_back(new Course(2,"sekond")); 
    cor.push_back(new Course(4,"third")); 
    cor.push_back(new Course(1,"fourth")); 
    cor.push_back(new Course(5,"fifth")); 
    sort (cor.begin(), cor.end()); 
    for (itcor=cor.begin(); itcor!=cor.end(); ++itcor) { 
     cout << *itcor << ' '; 
    } 
} 

例如,当我想排序他们正在按他们的地址排序的对象。

+0

“*我有一个向量包含类的对象*” - 不,它不。你的向量包含指向对象的指针,而不是对象。 –

+1

@ user1559792 - 要“接受”答案,请点击答案旁边的复选标记。要“回复”答案,请单击答案旁边的向上三角形。我认为你还没有接受任何答案。 –

+0

哦,我不知道。我认为“有帮助”的按钮是正确的。 – user1559792

回答

0

您可以通过三种方式做到这一点:

1)过载<运营商,并调用的std ::排序算法。该代码将是这样的:

bool operator<(Course *a, Course *b) const { 
    // do comparison 
    return A_BOOL_VALUE; 
} 

std::sort(array_of_courses.begin(),array_of_courses.end()); 

第一种方式是错误的,因为你不能在指针超载<操作。

2)创建一个比较函数,然后调用std::sort的第二个版本。代码如下所示:

bool compare(Course *a,Course *b) { 
    // do comparison 
    return A_BOOL_VALUE; 
} 

std::sort(array_of_courses.begin(),array_of_courses.end(),compare); 

3)创建一个比较类,它有它的()运营商超载,然后调用std::sort第三优化版本。代码:

struct Compare { 
    bool operator()(Course *a, Course *b) { 
    // do comparison 
    return A_BOOL_VALUE; 
    } 
}; 

std::sort(array_of_courses.begin(),array_of_courses.end(),Compare); 

注:排序功能在algorithm头文件中找到。

+0

您是否注意到OP有*指针向量*,而不是*对象*向量? –

+0

这些签名需要为OP的代码采用'Course *',并且我假定它们应该是'Course const&',否则匹配'operator <'? – Useless

+1

-1除了作为指针向量的向量之外,您不会将类名作为参数传递给'sort'。 –

4

您需要为std::sort方法提供自定义比较器类或函数,以使其不按地址排序。

template <class RandomAccessIterator, class Compare> 
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp); 

其中comp可以定义为:

bool comparer(const Course* x, const Course* y) { /*compare*/ } 
//or 
struct comparer { 
    bool operator() (const Course* x, const Course* y) { /*compare*/ } 
} comparerObject; 

和排序为拨打:

std::sort(cor.begin(), cor.end(), comparer); //method alternative 

std::sort(cor.begin(), cor.end(), comparerObject); //class alternative 

也就是说,或者不保持在指针vector。从您发布的代码,目前尚不清楚您是否真的需要指针:

vector<Course> cor; 

应该足够了。

+0

或'std :: sort(cor.begin(),cor。end(),comparer());' –