基本操作汇总

常见函数

max与max_element:

max(a,b),返回a,b两者之间的较大值
max_element(first, end),返回first和end之间的最大值的迭代器(其中first和end均为迭代器),也可用于寻找最大值所在索引

对于数组D[10]来说,使用res = max_element(D,D+6),即返回数组[0, 6)之间的最大值所在迭代器res,(res - D) 即为索引值。

对于向量vector来说,使用begin()、end()作为参数,实例如下:

vector<int>D;
vector<int>::iterator res = max_element(D.begin(),D.end())
dis = '最大值为:*res, 对应索引为 res - D.begin() 或 distance(D.begin(),res )'

同理,对应有min和min_element是求取最小值及所在索引。

accumulate求和函数

该函数在头文件#include <numeric> 里,主要是用来累加容器里面的值,比如int、string之类,可以少写一个for循环

比如直接统计vector<int> v 里面所有元素的和:(第三个参数的0表示sum的初始值为0,同时也代表结果的类型

int sum = accumulate(v.begin(), v.end(), 0);

比如直接将vector<string> v 里面所有元素一个个累加到string str中:(第三个元素表示str的初始值为空字符串)

string str = accumulate(v.begin(), v.end(), "");

猜你喜欢

转载自blog.csdn.net/Yanpr919/article/details/113477061