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));
相关推荐
ysa051030几秒前
二分+前缀(预处理神力2)
数据结构·c++·笔记·算法
2401_833197732 分钟前
嵌入式C++电源管理
开发语言·c++·算法
灰色小旋风6 分钟前
力扣22 括号生成(C++)
开发语言·数据结构·c++·算法·leetcode
寒月小酒7 分钟前
3.23 OJ
数据结构·c++·算法
2501_924952697 分钟前
模板编译期哈希计算
开发语言·c++·算法
xiaoye-duck10 分钟前
C++ STL map 系列深度解析:从底层原理、核心接口到实战场景
开发语言·c++·stl
2201_7586426414 分钟前
嵌入式C++开发注意事项
开发语言·c++·算法
AI科技星27 分钟前
基于v≡c第一性原理的大统一力方程:严格推导、全维度验证与四大基本相互作用的统一
人工智能·线性代数·算法·机器学习·平面
小杍随笔28 分钟前
【Rust 语言编程知识与应用:同步机制详解】
开发语言·算法·rust
sprite_雪碧30 分钟前
枚举 / 搜索类算法(机试核心考点)
算法