c++ - 打印 std::array

标签 c++ arrays c++11

因此,在使用 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;
}

但是,每当我尝试运行它时,我都会收到以下错误:

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

关于此错误的含义以及我将如何修复它有什么想法吗?

如果我将 operator<< 替换为 template<...> print_array(const 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>&)

最佳答案

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

关于c++ - 打印 std::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19152178/

相关文章:

c++ - 检查服务是否来自 Microsoft

c++ - 字符串与特殊字符的匹配

c++ - 为什么我的复制构造函数不能使用新的调用并且具有相同的内存地址?

javascript - UseState 如何将数组设置回空?

c++ - g++ 编译错误 : `.rodata' can not be used when making a shared object; recompile with -fPIC

c++ - 任意算术类型比较 : does anyone know an implementation?

python - 如何将用 C++ 编写的函数 ("noblock") 导入 GRC

php - php中更干净的字母数组

排列数组中元素的算法

c++ - 使用 std::async 调用模板函数的正确方法是什么