8
所以,雖然有性病::陣列玩弄,我想要一個簡單的方法來打印出數組的所有元素,並嘗試以下操作:打印一個std ::陣列
using namespace std;
template <class T, int N>
ostream& operator<<(ostream& o, const array<T, N>& arr)
{
copy(arr.cbegin(), arr.cend(), ostream_iterator<T>(o, " "));
return o;
}
int main()
{
array<int, 3> arr {1, 2, 3};
cout << arr;
}
但是,每當我嘗試運行此操作,我得到以下錯誤:
test.cpp: In function 'int main()':
test.cpp:21:10: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
c:\mingw\bin\../lib/gcc/mingw32/4.6.2/include/c++/ostream:581:5: error: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char, _Traits = std::char_traits<char>, _Tp = std::array<int, 3u>]'
有關此錯誤意味着什麼以及我如何解決它的任何想法?
如果我有一個函數替換操作< <像模板< ...> print_array(常量數組&),誤差變化:
test.cpp: In function 'int main()':
test.cpp:20:17: error: no matching function for call to 'print_array(std::array<int, 3u>&)'
test.cpp:20:17: note: candidate is:
test.cpp:12:6: note: template<class T, int N> void print_array(const std::array<T, N>&)
它是哪個編譯器?因爲您的代碼編譯並在Visual C++ 2012上運行。 – Alex
std :: array是''而不是''。可能是你的編譯器找不到匹配項。你能升級到4.7甚至4.8嗎? 4.6不完全符合C++ 11。 –
適用於[IDEONE](http://ideone.com/9JzUr9),儘管我必須將'int'更改爲'size_t'。 – jxh