当前位置: 首页 > article >正文

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; // 输出:3
    std::cout << "Upper bound: " << *ub << std::endl; // 输出:4
}

在这里插入图片描述


http://www.kler.cn/a/554605.html

相关文章:

  • 上海市计算机学会竞赛平台2025年1月月赛丙组音乐播放
  • 机器学习_12 逻辑回归知识点总结
  • 【精调】LLaMA-Factory 快速开始1: Meta-Llama-3.1-8B-Instruct
  • 【QT】第一个 QT程序(对象树)
  • Moonshot AI 新突破:MoBA 为大语言模型长文本处理提效论文速读
  • UEFI Spec 学习笔记---9 - Protocols — EFI Loaded Image
  • [特殊字符]边缘计算课程资料整理|从零到实战全攻略[特殊字符]
  • 【Linux】【网络】不同子网下的客户端和服务器通信
  • 爬虫FirstDay01-Request请求模块详解
  • 网易严选DevOps实践:从传统到云原生的演进
  • 如何利用ArcGIS Pro打造萤火虫风格地图
  • 二叉树层序遍历的三种情况(总结)
  • 蓝桥杯备考:递归初阶
  • Vue.js Vue 测试工具:Vue Test Utils 与 Jest
  • 学习threejs,THREE.Material材质基类详解
  • 费曼学习法1 - 你好,PIL!图像处理的魔法棒 (入门篇)
  • 右键管家深度评测:打造个性化Windows右键菜单的高效工具
  • 论文略读:MoE-LLaVA:MixtureofExpertsforLargeVision-LanguageModels
  • requestAnimationFrame(rAF)使用,与传统方法(如 setTimeout/setInterval),直观展示 rAF 的优势
  • C++:使用 SFML 创建强化学习迷宫场景