Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why c++ accumulate third argument type cause compile failed

Tags:

c++

I write following codes in my editor,but it can't be compiled,it alerts:

cannot convert 'std::basic_string<char, std::char_traits<char>, 
std::allocator<char> to 'const char*' in assignment|
||=== Build finished: 1 errors, 0 warnings ===|

Code:

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

using namespace std;

int main()
{

    std::vector<std::string> v;
    v.push_back(string("a"));
    v.push_back(string("b"));
    v.push_back(string("c"));

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

    std::cout << num;

    return 0;
}

I don't know why it can't be compiled,please someone help me.Thanks:)

like image 767
CrystalJake Avatar asked Dec 21 '22 04:12

CrystalJake


1 Answers

Paragraph 26.7.2/1 of the C++11 Standard specifies:

template <class InputIterator, class T>
T accumulate(InputIterator first, InputIterator last, T init);

[...]

1 Effects: Computes its result by initializing the accumulator acc with the initial value init and then modifies it with acc = acc + *i [...] for every iterator i in the range [first,last) in order.

[...]

String literals have type const char[], decaying to const char* when you pass them to functions. Therefore, the initializer you pass to accumulate() would be a const char*, and T would be a const char*.

This means acc from the expression above will be a const char*, and *i will be a string. Which means the following will not compile:

acc = acc + *i;

Because acc + *i yields a std::string, and on the left side of the assignment you have a const char*.

As other have suggested, you should do:

 string num = accumulate(v.begin(),v.end(),string());

Also, you do not need to do:

v.push_back(string("a"));

When inserting strings into the vector. This is enough:

v.push_back("a");

An std::string will be implicitly constructed from the string literal "a".

like image 184
Andy Prowl Avatar answered Jan 14 '23 00:01

Andy Prowl