欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > C++ STL中的reverse/unique/sort/lower_bound/upper_bound函数使用

C++ STL中的reverse/unique/sort/lower_bound/upper_bound函数使用

2025/2/21 19:46:15 来源:https://blog.csdn.net/nyxdsb/article/details/145764607  浏览:    关键词:C++ STL中的reverse/unique/sort/lower_bound/upper_bound函数使用

本文主要涉及以下几个函数:

  • reverse:反转序列。
  • unique:移除相邻重复元素。
  • sort:对序列进行排序。
  • lower_boundupper_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_boundupper_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; // 输出:3std::cout << "Upper bound: " << *ub << std::endl; // 输出:4
}

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词