STL 常用算法记录

本文介绍了C++标准模板库(STL)中的多个实用算法,包括accumulate、for_each、replace_if、count、find及binary_search等,并提供了具体的实现案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

accumulate

有的算法有两个版本,可以加入自己的比较函数改变原来算法的执行效果
在这里插入图片描述
测试函数

#include<iostream>
#include <numeric>
int func(int x, int y)
{
	return x + 2 * y;
}
struct testclass {
	int operator()(int x, int y) { return x + 3 * y; };
}obj;
using namespace std;
int main()
{
	int n = 100;
	int num[] = { 10,40,60 };
	cout << accumulate(num, num + 3,n,func);
	return 0;
}

for_each

在这里插入图片描述
测试函数

#include<iostream>
#include<vector>
#include<algorithm>

void func(int i)
{
	cout << i << "\t";
}
using namespace std;
int main()
{
	int n = 100;
	vector<int> v= { 10,40,60 };
	for_each(v.begin(), v.end(),func);
	return 0;
}

replace

在这里插入图片描述

replace_if

在这里插入图片描述pred是我们要传入的函数指针,名称Predicate暗示我们需要提供一个判断函数

测试函数

#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
void display(int i)
{
	cout << i << "\t";
}
bool func(int x)
{
	if (x % 2 == 0)
		return true;
	else
		return false;
}
int main()
{
	int n = 10;
	vector<int> v = { 10,25,35,40,50 };
	replace_if(v.begin(), v.end(), func, 5);	//偶数项全部变为5
	for_each(v.begin(), v.end(),display);

	return 0;
}

count

容器内部自带的count和find查找效率更快
在这里插入图片描述
count测试函数

#include<iostream>
#include<vector>
#include <algorithm>
#include<map>
using namespace std;

int main()
{
	int n = 10;
	//vector<int> v = { 10,25,35,40,50 };
	map<string, int> mp;
	mp["qwe"] = 100;
	mp["asd"] = 200;
	mp["zxc"] = 300;
	string s = "qwe";
	//cout<<count(mp.begin(), mp.end(),s )<<endl;	//此处编译不通过
	cout << mp.count(s) << endl;	//返回1

	return 0;
}

find

在这里插入图片描述find_if测试函数

#include<iostream>
#include<vector>
#include <algorithm>
#include<map>
using namespace std;

bool func(int& value)
{
	return value % 9 == 0 ? 1 : 0;
}
int main()
{
	int n = 10;
	vector<int> v = { 10,25,72,35,40,50 };
	cout<<find_if(v.begin(), v.end(), func)-v.begin();	//找到数组中第一个9的整数
	return 0;
}

binary_search 二分查找

lower_bound()返回不大于查找value的第一个元素

upper_bound()返回大于查找value的第一个元素

这样的设定可以让两个函数返回的值在另外的算法中满足前闭后开标准。

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值