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));
相关推荐
TracyCoder1237 小时前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
u0109272718 小时前
C++中的策略模式变体
开发语言·c++·算法
2501_941837268 小时前
停车场车辆检测与识别系统-YOLOv26算法改进与应用分析
算法·yolo
Aevget9 小时前
MFC扩展库BCGControlBar Pro v37.2新版亮点:控件功能进一步升级
c++·mfc·界面控件
六义义9 小时前
java基础十二
java·数据结构·算法
四维碎片9 小时前
QSettings + INI 笔记
笔记·qt·算法
Tansmjs9 小时前
C++与GPU计算(CUDA)
开发语言·c++·算法
独自破碎E10 小时前
【优先级队列】主持人调度(二)
算法
weixin_4454766810 小时前
leetCode每日一题——边反转的最小成本
算法·leetcode·职场和发展
打工的小王10 小时前
LeetCode Hot100(一)二分查找
算法·leetcode·职场和发展