通过对象的属性对对象的向量进行排序 [英] Sort a vector of objects by an object's attribute

查看:83
本文介绍了通过对象的属性对对象的向量进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何使用std :: sort和结构向量和比较函数?

我有一个cat对象(什么?)和一个catSort对象,它明显地排序cat对象。下面是类

I have a cat object (what?) and a catSort object which obviously sorts the cat objects. Below is the classes

class cat {
public:
    int age;
};

class catSorter {
public:
    vector< cat > cats;
    vector< cat > SortCatsByAge();
    void AddCat( cat new_cat );
};

void catSorter::AddCat(cat new_cat){
    this->cats.push_back(new_cat)
}

vector< cat > catSorter::SortCatsByAge(){
    // Sort cats here by age!
}


cat tim;
tim.age = 10;

cat mark;
mark.age = 20

cat phil;
phil.age = 3;

catSorter sorter;
sorter->AddCat(tim);
sorter->AddCat(mark);
sorter->AddCat(phil);

std::<vector> sortedcats = sorter->SortCatsByAge();

我在排序向量时遇到问题,我该怎么办?我应该循环遍历 cats 属性并将它们存储在临时向量中,然后返回?

I'm having difficulties sorting a vector, how would I go about doing this? Should I just loop through the cats attribute and store them inside a temporary vector then return that? Is there an easier way to do this?

推荐答案

您应该实现一个运算符< 在cat上,以便cats可以排序:

You should implement an operator< on cat so that cats can be sorted:

class cat {
public:
    int age;
    bool operator< (const cat &other) const {
        return age < other.age;
    }
};

然后,您可以包含算法标题,并使用 std :: sort

You can then include the "algorithm" header and use std::sort on your array:

vector< cat > catSorter::SortCatsByAge(){
   vector< cat > cats_copy = cats;
   std::sort(cats_copy.begin(), cats_copy.end());
   return cats_copy;
}

这篇关于通过对象的属性对对象的向量进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆