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:)
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 iteratori
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With