请自定义pair类并重载小于号,利用stl中的sort函数完成
时间: 2024-11-19 10:35:27 浏览: 27
在C++中,我们可以自定义一个Pair类,并重载`<`运算符,以便支持`std::sort`函数的使用。以下是一个例子,定义了一个名为`CustomPair`的类,其中包含两个整数成员,并实现了自定义的比较规则:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
class CustomPair {
public:
int first;
int second;
// 自定义构造函数
CustomPair(int a, int b) : first(a), second(b) {}
// 重载 '<' 运算符,按照 'first' 成员进行升序比较,如果 'first' 相同,则比较 'second'
bool operator<(const CustomPair &other) const {
if (this->first != other.first)
return this->first < other.first;
else
return this->second < other.second;
}
};
void sortCustomPairs(std::vector<CustomPair>& pairs) {
std::sort(pairs.begin(), pairs.end());
for (const auto &pair : pairs) {
std::cout << "Sorted Pair: (" << pair.first << ", " << pair.second << ")\n";
}
}
int main() {
int N;
std::cout << "Enter the number of CustomPairs: ";
std::cin >> N;
std::vector<CustomPair> customPairs(N);
for (int i = 0; i < N; ++i) {
int a, b;
std::cout << "Enter values for CustomPair " << i+1 << ": ";
std::cin >> a >> b;
customPairs[i] = CustomPair(a, b);
}
sortCustomPairs(customPairs);
return 0;
}
```
在这个例子中,用户输入一对对的整数值,它们会被存储在`CustomPair`对象中,然后通过自定义的`<`运算符进行排序。当`std::sort`看到这种自定义类型的容器时,会调用我们提供的`operator<`来进行比较。
阅读全文
相关推荐

















