按对象的属性对对象向量进行排序

Sort a vector of objects by an object's attribute

本文关键字:对象 排序 向量 属性      更新时间:2023-10-16

可能重复:
如何使用std::sort与结构向量和比较函数?

我有一个cat对象(什么?)和一个catSort对象,它显然对cat对象进行了排序。以下是类

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属性并将它们存储在一个临时向量中,然后返回吗?有更简单的方法吗?

您应该在cat上实现一个operator<,以便对cat进行排序:

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

然后,您可以在数组中包含"算法"标头并使用std::sort

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