在C++中,你可以通過創建一個自定義的比較函數或比較類來定義std::set
的排序規則
方法1:使用比較函數
#include <iostream>
#include <set>
#include <vector>
// 自定義比較函數
bool my_compare(int a, int b) {
return a < b;
}
int main() {
// 使用自定義比較函數創建set
std::set<int, decltype(&my_compare)> my_set(my_compare);
// 向set中添加元素
my_set.insert(5);
my_set.insert(3);
my_set.insert(8);
my_set.insert(1);
// 輸出set中的元素(按自定義排序規則)
for (const auto& elem : my_set) {
std::cout << elem << " ";
}
return 0;
}
方法2:使用比較類
#include <iostream>
#include <set>
#include <vector>
// 自定義比較類
struct MyCompare {
bool operator()(int a, int b) const {
return a < b;
}
};
int main() {
// 使用自定義比較類創建set
std::set<int, MyCompare> my_set(MyCompare());
// 向set中添加元素
my_set.insert(5);
my_set.insert(3);
my_set.insert(8);
my_set.insert(1);
// 輸出set中的元素(按自定義排序規則)
for (const auto& elem : my_set) {
std::cout << elem << " ";
}
return 0;
}
在這兩個示例中,我們都定義了一個自定義排序規則,使得std::set
中的元素按升序排列。你可以根據需要修改比較函數或比較類,以實現不同的排序規則。