面试题答案
一键面试#include <iostream>
#include <vector>
#include <algorithm>
class DescendingSortWithThreshold {
private:
int threshold;
public:
DescendingSortWithThreshold(int th) : threshold(th) {}
// 拷贝构造函数
DescendingSortWithThreshold(const DescendingSortWithThreshold& other) : threshold(other.threshold) {}
// 赋值运算符重载
DescendingSortWithThreshold& operator=(const DescendingSortWithThreshold& other) {
if (this != &other) {
threshold = other.threshold;
}
return *this;
}
bool operator()(int a, int b) const {
if (a > threshold && b <= threshold) {
return true;
} else if (a <= threshold && b > threshold) {
return false;
}
return a > b;
}
};
void sortVectorDescendingWithThreshold(std::vector<int>& vec, int threshold) {
DescendingSortWithThreshold sorter(threshold);
std::sort(vec.begin(), vec.end(), sorter);
}
你可以这样调用:
int main() {
std::vector<int> vec = {1, 5, 3, 7, 4, 9, 2};
int threshold = 5;
sortVectorDescendingWithThreshold(vec, threshold);
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
拷贝构造和赋值操作的意义
- 拷贝构造函数:
- 实际应用意义:在函数传参和返回对象时,拷贝构造函数会被调用。例如,当一个函数以值传递的方式接收一个函数对象,或者以值返回的方式返回一个函数对象时,拷贝构造函数会创建一个新的对象副本。这确保了函数内部对函数对象的操作不会影响到原始对象,并且可以在不同的作用域中使用相同逻辑的函数对象。
- 赋值操作:
- 实际应用意义:赋值操作允许在对象已经存在的情况下,将其状态更改为另一个对象的状态。这在需要动态改变函数对象的某些参数(如阈值)时很有用。例如,你可能在程序运行过程中根据不同的条件,将一个函数对象赋值为具有不同阈值的另一个函数对象,从而改变排序逻辑。