如何重写compare
时间: 2024-05-03 18:20:45 浏览: 8
函数来排序一个自定义对象列表?
我们可以为自定义对象编写一个比较函数,然后使用该函数进行排序。可以使用C++中的STL库中的sort函数来进行排序操作,在sort函数中传入自定义比较函数即可。
下面是一个示例代码:
```c++
class MyClass
{
public:
int val;
MyClass(int v) : val(v) {}
bool operator<(const MyClass& other) const
{
return val < other.val;
}
};
bool compareFunc(const MyClass& a, const MyClass& b)
{
return a.val < b.val;
}
int main()
{
std::vector<MyClass> myList;
myList.push_back(MyClass(3));
myList.push_back(MyClass(1));
myList.push_back(MyClass(2));
// 排序前输出
for (const auto& it : myList)
{
std::cout << it.val << " ";
}
// 使用STL库中的sort函数排序并输出
std::sort(myList.begin(), myList.end(), compareFunc);
std::cout << std::endl << "排序后: ";
for (const auto& it : myList)
{
std::cout << it.val << " ";
}
}
```
输出如下:
```
3 1 2
排序后: 1 2 3
```
当然,你可以根据自定义对象的成员变量编写不同的比较函数,以适应不同场景的排序需求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)