一、使用快排代替默认排序
默认的排序方法通常是使用红黑树等数据结构实现的,时间复杂度为O(nlogn),但是如果使用快速排序的话,时间复杂度可以降为O(nlogn),在处理大量数据时,这种提升是非常显著的。
#include <set>
#include <algorithm>
template <typename T>
void QuickSort(std::set<T>& s)
{
std::vector<T> elements;
elements.reserve(s.size());
for (auto it = s.begin(); it != s.end(); ++it) {
elements.push_back(std::move(*it));
}
std::sort(std::begin(elements), std::end(elements));
s.clear();
for (auto& elem : elements) {
s.insert(std::move(elem));
}
}
二、使用自定义的比较函数
当set存储的是自定义的数据类型时,可以使用自定义的比较函数代替默认的比较方式,这样可以更加高效地完成排序。
struct Person {
int age;
std::string name;
bool operator <(const Person& other) const
{
return age < other.age;
}
};
struct PersonCompare {
bool operator()(const Person& lhs, const Person& rhs) const
{
return lhs.age < rhs.age;
}
};
std::set<Person, PersonCompare> people;
三、使用emplace代替insert
当插入新的元素时,可以使用emplace代替insert,这样可以避免临时对象的创建和销毁,提高代码的效率。
std::set<int> s;
s.emplace(42);
s.emplace(1337);
四、使用lower_bound和upper_bound代替find
当查找特定元素时,可以使用lower_bound和upper_bound代替find,这样既可以找到等于指定值的元素,也可以找到第一个大于指定值的元素。
std::set<int> s = {1, 2, 4, 8, 16};
auto lower = s.lower_bound(4); // returns iterator to 4
auto upper = s.upper_bound(4); // returns iterator to 8
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/192507.html