面试题答案
一键面试- 方法:
- 在C++中,
std::set
默认使用std::less
进行比较,实现升序排序。要实现降序排序,可以自定义比较函数,使用std::greater
。
- 在C++中,
- 代码示例:
#include <iostream>
#include <set>
int main() {
// 使用std::greater作为比较函数,创建降序排序的set
std::set<int, std::greater<int>> mySet;
mySet.insert(3);
mySet.insert(1);
mySet.insert(2);
for (int num : mySet) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
上述代码中,std::set<int, std::greater<int>> mySet;
定义了一个std::set
,第二个模板参数std::greater<int>
指定了按降序比较元素。然后插入一些元素并遍历输出,可以看到元素是按降序排列的。