c++ - Cout 不起作用 - (错误:'operator<<' 不匹配)
问题描述
我正在努力学习 C++。我明白了几件事。
我试图在 C++ 中使用向量来实现动态数组的程序,虽然一切似乎都正常,但特定cout
语句中的一件事会引发一些奇怪的错误。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> g1;
for (int i = 1; i <= 5; i++) {
g1.push_back(i);
}
cout << "This works"; // this cout works
cout << g1; // but this does not why ?
return 0;
}
运行后出现的错误。
main.cpp: In function ‘int main()’:
main.cpp:18:7: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::vector<int>’)
cout << g1;
~~~~~^~~~~
这是程序。我试图在hackerrank上调试,我遇到了这个问题。为什么 cout 仅适用于向量变量?我错过了什么?
解决方案
operator<<
for没有重载std::vector<T>
。如果你真的想使用operator<<
for std::vector<T>
,你必须自己提供实现,例如:
template <typename T>
std::ostream& operator<< (std::ostream& out, const std::vector<T>& vec) {
if ( !vec.empty() ) {
out << '{';
std::copy (std::cbegin(vec),
std::cend(vec),
std::ostream_iterator<T>(out, ", "));
out << "}";
}
return out;
}
推荐阅读
- jsf - 带有确认对话框的 JSF inputSwitch
- javascript - “{machine_id} 的节点标识符是 {id}”执行 node.js 程序时出错
- tensorflow - TF 准确度得分和混淆矩阵不一致。TensorFlow 是否会在 BatchDataset 的每次访问时对数据进行洗牌?
- git - 在 github 上合并拉取请求并保持历史记录一致
- virtualbox - 将 VirtualBox .VDI .VHD .VMDK 转换为 BOOTABLE .iso 文件
- django - 保存时对相关模型执行操作
- ssl - 带有 .cer 异常的卷曲 TLS
- mysql - 计算字段的优化排序
- r - 保存 kable 表的问题 (install_phantomjs)
- html - 将背景图像与表格 td 元素的右侧对齐