给定数组 求和等于固定值 算法_C ++魔术师STL算法(一)

不知道大家有没有了解竞争性编程?

对于所有库函数,STL都有大量的算法。

874a69c160fdf71e4030fc45439ae5aa.png

以下是一些关于向量的最常用算法和《竞争性编程》中最有用的算法:

非操纵算法:

1.sort(first_iterator,last_iterator) –对给定向量进行排序。

2.reverse(first_iterator,last_iterator) –反转向量。

3.* max_element(first_iterator,last_iterator) –查找向量的最大元素。

4.* min_element(first_iterator,last_iterator) –查找向量的最小元素。

5.accumulate(first_iterator,last_iterator,求和的初始值) –对向量元素求和

// 一个C++程序来演示sort()的工作方式#include  #include  #include  #include  //用于累加运算using namespace std; int main() { // 用数组值初始化流量int arr[] = {10, 20, 5, 23 ,42 , 15}; int n = sizeof(arr)/sizeof(arr[0]); vector vect(arr, arr+n); cout << "Vector is: "; for (int i=0; i

6.count(first_iterator,last_iterator,x) –计算向量中x的出现。

7.find(first_iterator,last_iterator,x) –如果向量中不存在元素,则指向向量((name_of_vector).end())的最后地址。

// C++程序来演示count()的工作方式#include  #include  #include  using namespace std; int main() { //用数组值初始化向量int arr[] = {10, 20, 5, 23 ,42, 20, 15}; int n = sizeof(arr)/sizeof(arr[0]); vector vect(arr, arr+n); cout << "Occurrences of 20 in vector : "; // 计算从1st到20的出现次数 //最后一个元素cout << count(vect.begin(), vect.end(), 20); // find() 将迭代器返回到最后一个地址// 元素不存在find(vect.begin(), vect.end(),5) != vect.end()? cout << "Element found": cout << "Element not found"; return 0; }

8.binary_search(first_iterator,last_iterator,x) –测试x是否存在于排序的向量中。

9.lower_bound(first_iterator,last_iterator,x) –返回一个迭代器,该迭代器指向[first,last)范围内第一个元素,该元素的值不小于'x'。

10.upper_bound(first_iterator,last_iterator,x) –返回一个迭代器,该迭代器指向[first,last)范围内第一个元素的值大于'x'。

// 用C++程序来演示 lower_bound() 的工作//和 upper_bound(). #include  #include  #include  using namespace std; int main() { // 用数组值初始化向量 int arr[] = {5, 10, 15, 20, 20, 23, 42, 45}; int n = sizeof(arr)/sizeof(arr[0]); vector vect(arr, arr+n); //对数组值进行排序,以确保lower_bound() // 和upper_bound() 一起运行sort(vect.begin(), vect.end()); // 返回第一次出现得 20 auto q = lower_bound(vect.begin(), vect.end(), 20); // 返回最后一次出现得 20 auto p = upper_bound(vect.begin(), vect.end(), 20); cout << "The lower bound is at position: "; cout << q-vect.begin() << endl; cout << "The upper bound is at position: "; cout << p-vect.begin() << endl; return 0; } 

还有一些算法因为篇幅原因,留在下篇介绍,您可以关注我,当然也可以通过点击下方链接领取免费学习资料以及教程:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值