使用 vector 重载 << 时的 C++ 错误

标签 c++ vector operator-overloading

我正在尝试使用 vector 和 << 运算符来显示基本的 3 x 3 矩阵。问题是当我尝试运行代码时出现错误,指出 MatrixViaVector 中没有名为 size 的成员。

在我的头文件中我有:

#ifndef homework7_MatrixViaVector_h
#define homework7_MatrixViaVector_h

#include<iostream>
#include<fstream>
#include<string>
#include <cstdlib>
#include <vector>

using namespace std;
template <class T>

class MatrixViaVector{

public:
    MatrixViaVector();
    MatrixViaVector(int m,int n);
    template <class H>
    friend ostream& operator <<(ostream& outs, const MatrixViaVector<H> &obj);
private:
    int m,n;
    vector<vector<T>> matrix;
};

#endif

在我的测试文件中我有:

    #include "MatrixViaVector.h"

    template <class T>
    MatrixViaVector<T>::MatrixViaVector(){

        //creates a 3 by 3 matrix with elements equal to 0


        for (int i=0;i<3;i++){
            vector<int> row;
            for (int j=0;j<3;j++)
                row.push_back(0);
            matrix.push_back(row);
        }
    }

template <class T>
MatrixViaVector<T>::MatrixViaVector(int m,int n)//creates a m by n matrix????
{
    //creates a matrix with dimensions m and n with elements equal to 0

    for (int i=0;i<m;i++){
        vector<int> row;
        for (int j=0;j<n;j++)
            row.push_back(0);
        matrix.push_back(row);
    }
}

    template <class T>
    ostream& operator <<(ostream& outs, const MatrixViaVector<T> & obj)
    {
        //obj shud have the vector and therefore I should be able to use its size

        for (int i = 0; i < obj.size(); i++){
            for (int j = 0; j < obj.capacity(); j++)
                outs << " "<< obj.matrix[i][j];
            outs<<endl;
        }
        outs<<endl;
        return outs;
    }

    int main()
    {

    MatrixViaVector <int> A;
    MatrixViaVector <int> Az(3,2);//created an object with dimensions 3by2????
    cout<<A<<endl;
    cout<<Az<<endl;//this prints out a 3 by 3 matrix which i dont get????????
    }

最佳答案

你的 MatrixViaVector<>没有功能 size() , 但如果您打算使用 vector 的大小,请执行以下操作:

更改此代码段:

for (int i = 0; i < obj.size(); i++){
        for (int j = 0; j < obj.capacity(); j++)
            outs << " "<< obj.matrix[i][j];
        outs<<endl;
    }

for (std::vector<int>::size_type i = 0; i < obj.matrix.size(); i++){
        for (std::vector<int>::size_type j = 0; j < obj.matrix.size(); j++)
            outs << " "<< obj.matrix[i][j];
        outs<<endl;
    }

std::vector::size()std::vector::capacity()是2个不同的函数,请检查它们的区别。

关于使用 vector 重载 << 时的 C++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31212704/

相关文章:

c++ - OpenCV:基于高斯混合模型的颜色提取

c++ - 使用 Qt 树模型存储数据?

c++ - 我如何使用这个独特的运算符重载函数

c++ - 重载运算符 == 和 != : compiler moans ambiguity

同一运算符的 C++ 多个运算符重载

c++11 decltype 返回引用类型

c++ - 如何在 CPP 实现中使用 MT(或类似)RNG 算法?

c++ - 计算总能量

c++ - 在数组中存储 n 个 vector

c++ - 在 OpenCV 中将 Mat 转换为数组/vector