c++ - 为 3D 数组中的特定元素创建对象

标签 c++ arrays multidimensional-array

我想通过指定 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/

相关文章:

复合赋值运算符的 C++ 概念

Javascript OOP 和数组

python - 非零值的 Numpy 总和运行长度

python - C++ 和 Python : Pass and return a 2D double pointer array from python to c++

c# - 在 C# 中更新多维字节数组

c++ - 用C++获取网站源码——内容重复

java - 将 C++ OpenGL 帧缓冲区代码移植到 LWJGL - 我使用什么类?

c - C中的char string [LENGTH]和char * string [LEN]有什么区别

swift - 在 Swift 中计算多维数组的维数

C++ 值初始化 vector 迭代器比较