21xrx.com
2024-09-20 00:48:50 Friday
登录
文章检索 我的文章 写文章
使用C++类来实现二维数组
2023-07-08 11:11:30 深夜i     --     --
C++ 二维数组 实现

二维数组是计算机科学中广泛使用的数据结构之一。C++是一种被广泛使用的编程语言,其支持面向对象编程(OOP)方式。在C++中,使用类来实现二维数组是一种有效的方法。下面将介绍如何使用C++类来实现二维数组。

首先,我们需要定义一个类,名为TwoDimensionalArray,该类应该具有以下属性:行数、列数和二维数组本身。在C++中,可以使用二维vector来实现二维数组。在类定义中,我们可以使用如下声明:


class TwoDimensionalArray {

  public:

    TwoDimensionalArray(int rowCount, int colCount);

    void setValue(int row, int col, int value);

    int getValue(int row, int col);

  private:

    vector<vector<int>> data;

    int rows;

    int cols;

};

首先,在类的构造函数中,应当初始化二维vector并设置行数和列数。可以使用vector的resize函数来达到这一目的:


TwoDimensionalArray::TwoDimensionalArray(int rowCount, int colCount) {

  this->data.resize(rowCount);

  for (int i = 0; i < rowCount; i++) {

    this->data[i].resize(colCount);

  }

  this->rows = rowCount;

  this->cols = colCount;

}

接下来,需要提供函数用来设置和获取二维数组中的元素。因此,我们可以定义setValue和getValue函数:


void TwoDimensionalArray::setValue(int row, int col, int value) {

  this->data[row][col] = value;

}

int TwoDimensionalArray::getValue(int row, int col) {

  return this->data[row][col];

}

可以看出,getValue和setValue函数是非常简单的,并且将数据的读取和写入的过程封装到了类中,方便使用者直接调用类的方法操作数据。

最后,我们可以使用该类创建一个二维数组实例,例如:


TwoDimensionalArray myArray(3, 3);

myArray.setValue(0, 0, 1);

myArray.setValue(0, 1, 2);

myArray.setValue(0, 2, 3);

myArray.setValue(1, 0, 4);

myArray.setValue(1, 1, 5);

myArray.setValue(1, 2, 6);

myArray.setValue(2, 0, 7);

myArray.setValue(2, 1, 8);

myArray.setValue(2, 2, 9);

通过上面的代码,我们创建了一个3行3列的二维数组,并往其中填入了一些数据。此时我们就可以方便地使用getValue函数获取特定位置的值,例如:


cout << myArray.getValue(1, 2) << endl;

结果应该为6。

在实现二维数组的过程中,使用类的方式可以对数据进行封装,更加方便代码的使用;同时,这种方法也更加规范化、安全化、就是较为容易被人理解。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复