打印一个标准::数组
Printing an std::array
所以,在玩 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:mingwbin../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(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;
}
相关文章:
- 效率:标准::数组与标准::矢量
- 多维标准::数组的可变参数模板
- 声明后,gcc 的动态大小数组是否与标准数组有效相同?
- C++填充多维标准::数组
- 如何声明 2D 标准::数组
- 如何查找 2d 标准::数组中的列数
- 基于多维标准::数组的范围
- 如何按降序对标准数组进行排序 - C++ 11.
- 优雅地声明 2 维(甚至多维)标准::数组
- 如何将标准::数组转换为标准::元组?
- 获取别名标准::数组的大小
- 如何找到多维标准::数组的大小
- C++ constexpr:在编译时计算标准数组
- 标准::数组类上的堆栈溢出
- 2-D 标准::数组的支撑初始值设定项列表(C++)
- 标准::数组是否可安全返回
- C++ 将双倍转换为字符并替换为标准::数组
- 解压缩标准::数组
- 动态标准数组的大小
- 打印一个标准::数组