C++常用算法函数

1、排序 :std::sort

cpp 复制代码
#include <algorithm>
#include <vector>
 
std::vector<int> v = {4, 2, 5, 3, 1};
std::sort(v.begin(), v.end()); // 将v中的元素按升序排序

2、查找: std::find

cpp 复制代码
#include <algorithm>
#include <vector>
 
std::vector<int> v = {1, 2, 3, 4, 5};
auto it = std::find(v.begin(), v.end(), 3); // 查找元素3
if (it != v.end()) {
    // 找到元素
}

3、计数: std::count

cpp 复制代码
#include <algorithm>
#include <vector>
 
std::vector<int> v = {1, 2, 3, 3, 4, 5};
int countNum = std::count(v.begin(), v.end(), 3); // 计数元素3的个数

4、归约: std::accumulate

cpp 复制代码
#include <algorithm>
#include <numeric>
#include <vector>
 
std::vector<int> v = {1, 2, 3, 4, 5};
int sum = std::accumulate(v.begin(), v.end(), 0); // 计算元素总和

5、填充: std::fill

cpp 复制代码
#include <algorithm>
#include <vector>
 
std::vector<int> v(5);
std::fill(v.begin(), v.end(), 10); // 用10填充v中的所有元素

6、复制:std::copy

cpp 复制代码
#include <algorithm>
#include <numeric>
#include <vector>

std::vector<int> nums = {4, 2, 5, 3, 8, 9, 6};
std::vector<int> nums_copy(nums.size());
std::copy(nums.begin(), nums.end(), nums_copy.begin());

7、合并:std::merge

cpp 复制代码
#include <algorithm>
#include <numeric>
#include <vector>
// 分割和合并
std::vector<int> even, odd;
for (int num : nums) {
    if (num % 2 == 0) {
        even.push_back(num);
    } else {
        odd.push_back(num);
    }
}
// 分割完成,合并结果
std::vector<int> result;
std::merge(even.begin(), even.end(), odd.begin(), odd.end(), std::back_inserter(result));
相关推荐
Flame_Cyclone5 分钟前
编写XBOX控制器实现鼠标键盘输入
c++·windows·win32·xbox·控制器模拟键盘鼠标
贩卖纯净水.6 分钟前
共享内存喜欢沙县小吃
linux·运维·服务器·c++
Dola_Pan8 分钟前
C++ STL-deque容器入门详解
开发语言·c++
玫瑰花店13 分钟前
OpengGL教程(三)---使用VAO和VBO方式绘制三角形
c++·ubuntu·计算机视觉·cmake·opengl
1750633194514 分钟前
Matlab/Simulink中PMSM模型的反电动势系数和转矩系数
算法·机器学习·matlab
岸边的风28 分钟前
前端Excel热成像数据展示及插值算法
前端·算法·excel
不是仙人的闲人29 分钟前
Qt 实现自定义截图工具
开发语言·c++·qt
一直在找资料的菜鸟1 小时前
VSCode创建C++项目和编译多文件
c++·vscode
wheeldown1 小时前
【C语言】(指针系列3)数组指针+函数指针+typedef+函数数组指针+转移表
c语言·数据结构·算法
陈小也~2 小时前
嵌入式-QT学习-小练习
linux·c++·qt