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));
相关推荐
耶叶15 分钟前
餐厅出入最少人数问题:贪心算法
算法·贪心算法
gihigo199819 分钟前
基于小波框架与稀疏表示的SAR图像目标识别系统(MATLAB实现)
算法
吴可可12336 分钟前
CAD2004自定义实体开发环境配置
c++·算法
装不满的克莱因瓶37 分钟前
矩阵的主成分是什么?主成分分析(PCA)又能做什么?
人工智能·线性代数·算法·机器学习·ai·矩阵·pca
大菜菜小个子42 分钟前
template<typename T>使用
java·开发语言·算法
L_09071 小时前
【C++】C++11 新特性
开发语言·c++
Fanfanaas1 小时前
C++ 继承
java·开发语言·jvm·c++·学习·算法
lqqjuly1 小时前
模型合并与融合:理论、算法与可运行实现—从损失曲面几何到多模型融合
算法
memcpy01 小时前
LeetCode 2144. 打折购买糖果的最小开销【贪心】
算法·leetcode·职场和发展
十五年专注C++开发1 小时前
cereal 库:C++ 序列化的轻量之选
开发语言·c++·序列化·反序列化·cereal