C++泛型函数

1.accumulate

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

using namespace std;

int main()
{
    vector<string> v;
    v.push_back("abc6");
    v.push_back("abc5");
    v.push_back("abc4");
    v.push_back("abc3");
    v.push_back("abc2");
    v.push_back("abc1");

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

这段代码是编译不通过的,原因是因为  字符串字面值的类型是 const char*,而+的类型是string类型,两者不兼容,报错信息是
cannot convert ‘std::basic_string<char>’ to ‘const char*’ in assignment|
string sum = accumulate(v.begin(),v.end()," ");
改成:
string sum = accumulate(v.begin(),v.end(),string(" "));
就OK了

你可能感兴趣的:(C++泛型函数)