按对象的属性对对象向量进行排序
Sort a vector of objects by an object's attribute
可能重复:
如何使用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;
}
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 对象接收堆栈溢出异常 c++ 的排序向量
- 如何使用 STL 排序对具有模板专用化的自定义类对象进行排序?
- 排序谓词没有传递对索引对象的引用?
- 使用指针指向对象C++对向量进行排序
- 按类成员的顺序对包含类对象的C++向量进行排序
- 无法使用接口类型对priority_queue中的对象进行排序<T>
- 基于不同字段的对象向量的排序功能
- 基于3个对象的自定义排序
- 尝试使用比较运算符对对象向量进行排序
- C++排序的对象集
- 从文件中读取并将其内容放入对象数组中,然后对它们进行排序
- q排序类对象的列表
- std::atexit 从全局对象的构造函数调用时的排序
- 尝试对对象数组进行排序时程序终止
- std::排序为排序自定义对象时出现的向量引发错误
- 通过其char键对对象指针的C 向量进行排序
- 排序算法,使用模板按内部数据对对象进行排序
- 在对象向量中的对象字段排序
- 如何使用 std::sort 对数组中的特定对象进行排序