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

dot*_*tty 5 c++ sorting vector

可能重复:
如何使用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();
Run Code Online (Sandbox Code Playgroud)

我在排序矢量时遇到困难,我该怎么做呢?我应该循环遍历cats属性并将它们存储在临时向量中然后返回吗?有更简单的方法吗?

mfo*_*ini 18

你应该实现一只operator<猫,以便猫可以分类:

class cat {
public:
    int age;
    bool operator< (const cat &other) const {
        return age < other.age;
    }
};
Run Code Online (Sandbox Code Playgroud)

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

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

  • 如果您无权访问`cat`类,或者出于不同目的想要按不同属性排序怎么办? (2认同)
  • @DrewNoakes可以将`operator &lt;`定义为一个自由函数,或者提供一个自定义的compare函数作为`std :: sort`的第三个参数。 (2认同)