zl程序教程

您现在的位置是:首页 >  其他

当前栏目

accumulate求和算法

2023-03-14 22:50:51 时间

accumulate求和算法

头文件:numeric 接受参数个数:三个

  • 前两个指出了需要求和的元素的范围,第三个参数是和的初值。
#include <iostream>
#include <vector>
#include<numeric>//注意包含头文件
using namespace std;
void test()
{
    vector<int> v = {1,2,3,4,5,6};
    cout << accumulate(v.begin(), v.end(), 0) << endl;
}
int main()
{
    test();
    system("pause");
    return 0;
}

accumulate的第三个参数的类型决定了函数中使用哪种加法运算符以及返回值的类型

注意:序列中元素的类型必须与第三个参数匹配,或者能够转换为第三个参数的类型。 上例中,v中的元素可以是int或者是double,long long或任何其他可以加到int上的类型

  • 由于string定义了+运算符,因此我们可以通过调用accumulate来将vector中所有的string元素连接起来
#include <iostream>
#include<numeric>//注意包含头文件
#include<string>
#include<vector>
using namespace std;
void test()
{
    vector<string> v = { "I"," ","want"," ","go"," ","back"," ","to"," ","past" };
    cout << accumulate(v.begin(), v.end(), string(""));
}
int main()
{
    test();
    system("pause");
    return 0;
}

注意:不能将空串当做一个字符串字面值传递给第三个参数,会导致一个编译错误

原因:

  • 如果我们传递了一个字符串字面值,用于和保存和的对象的类型是const char*,而const char*没有+运算符,此调用将产生错误。

总结:

  • 对于只读取而不改变元素的算法,通常最好使用cbegin()和cend()。
  • 但是如果你计算使用算法返回的迭代器来改变元素的值,就需要使用begin()和end()的结果作为参数。