C++STL中的reverse/unique/sort/lower_bound/upper_bound函数使用
- 人工智能
- 2025-08-25 18:06:02

本文主要涉及以下几个函数:
reverse:反转序列。unique:移除相邻重复元素。sort:对序列进行排序。lower_bound 和 upper_bound:查找目标值的边界位置。头文件均为<algorithm>1. reverse
功能:反转指定范围内的元素顺序。reverse 不会改变容器的大小,仅改变元素的顺序。
void reverse(BidirectionalIterator first, BidirectionalIterator last); #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; std::reverse(v.begin(), v.end()); for (auto i : v) { std::cout << i << " "; } // 输出:5 4 3 2 1 }2. unique
功能:移除相邻重复元素(不保证全局唯一性),返回调整后序列的末尾迭代器。
注意:unique 只能移除相邻的重复元素,因此通常需要先对容器进行排序。
ForwardIterator unique(ForwardIterator first, ForwardIterator last); #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 2, 3, 3, 4, 5}; std::vector<int>::iterator it = std::unique(v.begin(), v.end()); v.erase(it, v.end()); for (auto i : v) { std::cout << i << " "; } // 输出:1 2 3 4 5 }3. sort
功能:对指定范围内的元素进行排序,默认升序。
void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp = std::less<T>()); #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {5, 3, 8, 6, 2}; std::sort(v.begin(), v.end()); for (auto i : v) { std::cout << i << " "; } // 输出:2 3 5 6 8 }自定义排序规则:
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; }); // 降序4. lower_bound 和 upper_bound 函数
功能:分别查找第一个大于或等于目标值的元素位置,以及第一个大于目标值的元素位置。
注意:lower_bound 和 upper_bound 都要求输入序列是有序的。
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value); ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, const T& value); #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 2, 3, 4, 4, 5}; auto lb = std::lower_bound(v.begin(), v.end(), 3); // 第一个 >=3 的位置 auto ub = std::upper_bound(v.begin(), v.end(), 3); // 第一个 >3 的位置 std::cout << "Lower bound: " << *lb << std::endl; // 输出:3 std::cout << "Upper bound: " << *ub << std::endl; // 输出:4 }C++STL中的reverse/unique/sort/lower_bound/upper_bound函数使用由讯客互联人工智能栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“C++STL中的reverse/unique/sort/lower_bound/upper_bound函数使用”
上一篇
C++数据切片问题,Plus多态