二维向量中的运算符[] [英] Operator [] in two dimensional vector

查看:99
本文介绍了二维向量中的运算符[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在二维向量的情况下,我想创建一个运算符[].搜索之后,我发现不可能传递两个参数.我如何才能在主目录中获取m_matrix[i][j]的值?

I want to create an operator [] in the case of two dimensional vector. After searching, I have found that it's impossible to pass two arguments. How I can obtain the value of m_matrix[i][j] in the main?

相关代码:

class MyMatrix  
{
    public:            // Methods

        MyMatrix();
        ~MyMatrix();

        int operator[] (int n);

    private:          // Attributes

        int m_n;
        int m_m;

        std:: vector <std:: vector <int> > m_matrix;

};

int MyMatrix::operator[](int n, int m)  // in the cpp
{
    if (n>=0 && m>=0 && n<=m_n && m<=m_m)
    {
      return m_matrix[n-1][m-1];
    }
    else
    {   cout<<"******************"<<endl;
        cout<<"No valid index"<<endl;
        cout<<"******************"<<endl;
        return 0;
    }
}

...

mat_test1[2][2]; // for example in the main

这是怎么了?

推荐答案

要恢复评论,您可以执行以下操作:

To resume the comment, you may do:

class MyMatrix
{
public:

    // Other methods

    const std::vector<int>& operator[] (int m) const { return m_matrix.at(m); }
    std::vector<int>& operator[] (int m) { return m_matrix.at(m); }

    int operator () (int m, int n) const { return m_matrix.at(m).at(n); }
    int& operator () (int m, int n) { return m_matrix.at(m).at(n); }

private:
    std::vector<std::vector<int>> m_matrix;
};

注意:我使用at而不是[]来使用从向量进行的检查,因此它会引发超出范围访问的异常.

Note: I used at instead of [] to use the check from vector and so it throws exception for out of bound access.

然后使用它:

MyMatrix matrix(5, 4); // size of the matrix from constructor

matrix[0][1] = 42; // MyMatrix::operator [] followed by std::vector<int>::operator[]
matrix(2, 2) = 42; // MyMatrix::operator () (int, int);

在线示例.

这篇关于二维向量中的运算符[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆