c++ algorithm下的常用函数

本文详细介绍了C++中algorithm库中的常用函数,包括max、min、abs等基本操作,swap用于交换变量值,reverse实现数组或容器内元素的反转,fill用于批量赋值,sort进行排序,并提供了自定义排序规则的方法。

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

algorithm下的常用函数

max(x,y) 返回x y中的最大值,参数只能是两个,如果想比较x,y,z的最大值,可写为max(x,max(y,z))

min(x,y)同理,返回的是x,y中的最小值

abs(x)返回x的绝对值,x必须是整数 浮点数是math文件下的fabs

swap(x,y)用来交换x,y的值

reverse(it,it2)将数组指针在[it,it2)(不包括it2)之间的元素或容器的迭代器下在[it,it2)(不包括it2)范围的元素进行反转

fill()可以把数组或容器的某一段区间赋值为某个相同的值

例:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
  int a[4]={1,2,3,4};
  fill(a,a+4,1);
  for(int i=0;i<4;i++)
    cout<<a[i]<<" "; //输出为 1 1 1 1
}

sort(首元素,尾元素的下一个地址,[比较函数]),默认是从小到大排序

#include<algorithm>
using namespace std;
int main()
{
  int a[4]={1,5,3,4};
  sort(a,a+4);
  for(int i=0;i<4;i++)
    cout<<a[i]<<" ";//输出为 1 3 4 5
}

如果想要自己规定排序规则,则需要自己写比较函数

下面是规定按从大到小的顺序排序示例

#include<iostream>
#include<algorithm>
using namespace std;
bool compare(int x,int y)
{
    return x>y;
}
int main()
{
  int a[4]={1,5,3,4};
  sort(a,a+4,compare);
  for(int i=0;i<4;i++)
    cout<<a[i]<<" ";//输出为 5 4 3 1 
}

C++标准库中提供了许多常用的算法函数,这些函数可以用于对容器(如vector、list等)中的数据进行排序、查找、遍历等操作。以下是一些常用C++ algorithm函数: 1. `std::sort`:对容器中的元素进行排序,可以通过自定义比较函数来指定排序方式。 ```cpp std::vector<int> nums = {4, 2, 6, 1, 5}; std::sort(nums.begin(), nums.end()); // 默认升序排序 ``` 2. `std::binary_search`:在已排序的容器中进行二分查找,返回是否找到指定元素。 ```cpp std::vector<int> nums = {1, 2, 3, 4, 5}; bool found = std::binary_search(nums.begin(), nums.end(), 3); // true ``` 3. `std::find`:在容器中查找指定元素,返回第一个匹配元素的迭代器,如果没找到则返回容器末尾的迭代器。 ```cpp std::vector<int> nums = {1, 2, 3, 4, 5}; auto it = std::find(nums.begin(), nums.end(), 3); // 指向元素3的迭代器 ``` 4. `std::count`:统计容器中指定元素的个数。 ```cpp std::vector<int> nums = {1, 2, 2, 3, 2}; int count = std::count(nums.begin(), nums.end(), 2); // 3 ``` 5. `std::accumulate`:计算容器中元素的累加和,可以指定初始值。 ```cpp std::vector<int> nums = {1, 2, 3, 4, 5}; int sum = std::accumulate(nums.begin(), nums.end(), 0); // 15 ``` 6. `std::reverse`:将容器中的元素翻转。 ```cpp std::vector<int> nums = {1, 2, 3, 4, 5}; std::reverse(nums.begin(), nums.end()); // {5, 4, 3, 2, 1} ``` 这些函数只是C++ algorithm库中的一小部分,还有许多其他有用的函数可用于不同的操作。你可以查阅C++标准库文档以获取更详细的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值