简体   繁体   English

打印std :: array

[英]Printing an std::array

So, while playing around with std::array, I wanted an easy way to print out all elements of an array, and tried the following: 因此,在使用std :: array时,我想要一种简单的方法来打印出数组的所有元素,并尝试以下方法:

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

However, whenever I try to run this, I get the following errors: 但是,每当我尝试运行它时,我都会收到以下错误:

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>]'

Any ideas on what this error means, and how I would go about fixing it? 关于这个错误意味着什么,以及我将如何修复它的任何想法?

If I replace operator<< with a function like template<...> print_array(const array&), the error changes: 如果我用类似template <...> print_array(const array&)的函数替换operator <<,则错误会发生变化:

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>&)

Use std::size_t to help compiler to deduce types: 使用std::size_t帮助编译器推导出类型:

template <class T, std::size_t N>
ostream& operator<<(ostream& o, const array<T, N>& arr)
{
    copy(arr.cbegin(), arr.cend(), ostream_iterator<T>(o, " "));
    return o;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM