C++常用算法函数

1、排序 :std::sort

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

2、查找: std::find

#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

#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

#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

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

6、复制:std::copy

#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

#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));
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值