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));
相关推荐
飞Link1 小时前
什么是 PX4?一文了解 PX4 在空地协同中的作用
算法·无人机
进化中的刀盾兽1 小时前
从零实现 C++ Json-Rpc(十):把消息交给真实连接——MuduoConnection 与 ConnectionFactory
c++·rpc
一去不复返的通信er8 小时前
力扣-图论-岛屿数量
算法·leetcode·图论
青瓦梦滋8 小时前
WebSocket协议
linux·服务器·网络·c++·websocket·网络协议·http
程序 代码狂人10 小时前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
HDU-Dade11 小时前
【校招笔试真题】简要介绍 Self-Attention 的前沿算法
人工智能·算法
小郎君65813 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
算法
CodeYp201913 小时前
第15讲:二叉搜索树
开发语言·c++·二叉搜索树
邵奈一14 小时前
GPT-6.1 Terra速度是Sol的3倍,价格减半
算法
RaaS10014 小时前
Node.js Brotli RCE 漏洞自查指南:fetch、undici、axios 都在影响面,三分钟确认你的版本
人工智能·深度学习·算法