我想通过指定3D数组中的特定元素来检索两个变量(例如:var4和var5)。
我目前正在尝试通过为特定元素创建一个对象,然后创建一个类,该类根据该特定元素指定的对象检索name4和name5的值。有什么想法吗?
答案 0 :(得分:1)
您的3D容器应该在课堂内private
。然后,您的set()
函数会将Row
Column
Depth
作为参数以及您想要放在这些坐标中的实际Value
或indexes
并将其设置在私有容器中。与set()
一起,您需要另一个get()
函数。同样get()
应该使用三个参数indexes
,它将从私有容器中为您检索值。
使用此示例构思,您将看到会发生什么。
set(row, column, depth, value); // can be void
RetrievedValue = get(row, column, depth) // should return something
这是使用std::vector
的工作代码的基本代码:
#include <iostream>
#include <vector>
using namespace std;
class Whatever
{
private:
vector<vector<vector<int>>> MyVec; // 3D vector
public:
Whatever(int RowSize, int ColumnSize, int DepthSize); // default constructor
int get(int Row, int Column, int Depth);
void set(int Row, int Column, int Depth, int Value);
};
Whatever::Whatever(int RowSize, int ColumnSize, int DepthSize)
{
vector<int> TempDepth;
vector<vector<int>> TempColumn;
for (int i = 0; i < RowSize; i++)
{
for (int j = 0; j < ColumnSize; j++)
{
for (int k = 0; k < DepthSize; k++)
{
TempDepth.push_back(0); // add an integer zero to depth on every iteration
}
TempColumn.push_back(TempDepth); // add the whole depth to the column
TempDepth.clear(); // clear
}
this->MyVec.push_back(TempColumn); // add the whole column to the row
TempColumn.clear(); // clear
}
}
int Whatever::get(int Row, int Column, int Depth)
{
return this->MyVec[Row][Column][Depth]; // "get" the value from these indexes
}
void Whatever::set(int Row, int Column, int Depth, int Value)
{
this->MyVec[Row][Column][Depth] = Value; // "set" the Value in these indexes
}
int main()
{
int rowSize, columnSize, depthSize;
cout << "Please enter your desired row size, column size and depth size:\n";
cin >> rowSize >> columnSize >> depthSize;
Whatever MyObjectOfClassWhatever(rowSize, columnSize, depthSize); // create a local object and send the sizes for it's default constructor
// let's say you need "set" a value in [2][4][1]
MyObjectOfClassWhatever.set(2, 4, 1, 99);
// now you want to "get" a value in [2][4][1]
int RetreivedData = MyObjectOfClassWhatever.get(2, 4, 1); // you get it from within the class and assign it to a local variable
// now you can do whatever you want
return 0;
}