首页 > 解决方案 > 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 仅适用于向量变量?我错过了什么?

标签: c++c++11

解决方案


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

Demo Here


推荐阅读