我想通过指定 3D 数组中的特定元素来检索两个变量(例如:var4 和 var5)。
我目前正在尝试通过为特定元素创建一个对象,然后创建一个类来根据该特定元素指定的对象检索 name4 和 name5 的值来实现这一点。有什么想法吗?
最佳答案
您的 3D 容器在类中应该是private
。然后,您的 set()
函数会将 Row
Column
Depth
作为参数以及实际的 Value
您想放入那些坐标或 indexes
并将其设置在私有(private)容器中。除了 set()
,您还需要另一个函数,即 get()
。此外,get()
应采用三个参数,即 indexes
,它将为您从私有(private)容器中检索值。
使用这个示例想法,您将看到会发生什么。
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;
}
关于c++ - 为 3D 数组中的特定元素创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36225287/