【问题标题】:error c2679.Error 1 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::vector<_Ty>'错误 c2679.Error 1 错误 C2679: 二进制 '<<' : 未找到采用 'std::vector<_Ty>' 类型的右侧操作数的运算符
【发布时间】:2015-02-24 07:48:11
【问题描述】:

我在下面编写了这个简单的程序来使用向量,但是这里有错误任何人都可以帮忙吗?

#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

void main()
{
    vector<int>a(10,1);
    cout<<a<<endl;
}

【问题讨论】:

  • 如果你想知道如何输出一个向量,请参考this question
  • 错误信息很清楚 - 你不能使用
  • @LuboAntonov 如何显示任何矢量?你能给我发给初学者简单的第一阶段程序吗?谢谢

标签: c++


【解决方案1】:

没有运算符

ostream& operator<<(ostream& os, vector<int> const& v) {
    for (int i=0; i<v.size(); ++i) {
        os << v[i] <<  ", ";
    }
    return os;
}

将此代码放在您的 main 函数之前,它应该可以工作。

【讨论】:

    【解决方案2】:

    试试这个:

    std::ostream& operator<<(std::ostream& stream, std::vector<int> const& vec) {
        for (auto it = vec.begin(); it != vec.end(); it++) {
            stream << *it <<  " ";
        }
        return stream;
    }
    

    或者:

    template <typename T>
    std::ostream& operator<<(std::ostream& stream, std::vector<T> const& vec) {
        for (auto it = vec.begin(); it != vec.end(); it++) {
            stream << *it <<  " ";
        }
        return stream;
    }
    

    (但请确保

    如果你不想重载

    for (auto& item : a) {
        std::cout << item << " ";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多