2013-05-31 27 views
4

我寫以下在我的編輯代碼,但它不能被編譯,它提醒:爲什麼C++積累第三個參數類型原因編譯失敗

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

代碼:

#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; 
} 

我不不知道爲什麼不能編譯,請別人幫我。謝謝:)

+1

傳遞一個字符串而不是'「」'。 'string num = accumulate(v.begin(),v.end(),std :: string());' – juanchopanza

+0

請說明原因? – CrystalJake

+1

,因爲「」不是字符串而是char數組。 – UmNyobe

回答

6

款C++ 11標準規定的26.7.2/1:

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

[.. ]

1個影響:通過與初始值初始化初始化累加器ACC計算其結果,然後用 修改它每個迭代器i的範圍爲 [first,last)

[...]

字符串文字具有類型const char[],衰減到const char*,當你把它們傳遞給函數。因此,您傳遞給accumulate()的初始值將是const char*,而T將是const char*

這意味着acc從上面的表達將是一個const char**i將是一個string。這意味着以下不會編譯:

acc = acc + *i; 

因爲acc + *i產生一個std::string,並在分配的左側,你有一個const char*

至於其他的建議,你應該做的:

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

而且,你不需要做:

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

當插入串入載體。這是不夠的:

v.push_back("a"); 

std::string將字符串文字"a"隱式地構建。

+0

很好,我完全理解它。 – CrystalJake

+0

@CrystalJake:好的,很高興我能幫上忙! –

1

作爲第三個參數而不是"",明確地調用std::string()

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

std::accumulate的一個模板參數是返回類型,它將從第三個函數參數中推導出來。這也是一種應該能夠累積輸入迭代器範圍內的值的類型。在你的情況下,你的返回類型應該是std::string,但你通過"",這是一個const char[2]。這不是一種可以複製和用於積累的類型。

你可以通過解決這個問題的std::string

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

std::accumulate返回類型是一樣的第三個參數,它被推斷爲const char*在你的案件的類型(因爲你傳遞一個字符串文字)。

這意味着函數期望在內部使用const char* s,但迭代器範圍包含std::string s,所以它是barf。這就是爲什麼你必須在第三個參數傳遞正確類型(std::string):

string num = accumulate(v.begin(), v.end(), std::string()); 
相關問題