Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing an std::array

Tags:

c++

arrays

c++11

So, while playing around with std::array, I wanted an easy way to print out all elements of an array, and tried the following:

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:

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>&)
like image 505
Muhammad Faizan Avatar asked Oct 03 '13 06:10

Muhammad Faizan


Video Answer


1 Answers

Use std::size_t to help compiler to deduce types:

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;
}
like image 150
masoud Avatar answered Sep 27 '22 18:09

masoud