c++ - 按对象的属性对对象 vector 进行排序

标签 c++ sorting vector

<分区>

Possible Duplicate:
How to use std::sort with a vector of structures and compare function?

我有一个猫对象(什么?)和一个显然对猫对象进行排序的 catSort 对象。下面是类

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();

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

最佳答案

你应该实现一个 operator<在猫上,以便对猫进行分类:

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;
}

关于c++ - 按对象的属性对对象 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9706517/

相关文章:

c++ - 使用 fstream 从文件中读取多个值?

javascript - 如何将CSS规则插入javascript?

c - qsort比较功能不起作用

python - 通过传递列表作为键参数,使用sorted() 对列表进行排序

c - 使用 union 结构的可扩展映射 vector

c++ - 在 C++ 中,是否有一种惯用的方法来防止运行操作集合导致集合发生变异的情况?

c++ - 我不断收到错误消息,这是我第一次使用类,这是我的代码 :

c++ - 如何高效地将元素插入到数组的任意位置?

matrix - 如何使用 Spark 的 RDD 与向量执行矩阵点积

c++ - 为什么插入 set<vector<string>> 这么慢?