簡體   English   中英

c ++ 3d數組函數返回

[英]c++ 3d array function returns

所以我有這個 3 維數組,看起來像這樣:

int map[100][100][100];

我想將它用作函數的返回類型,無論是作為指針還是類似的東西:

int* World::CreateCell() {

    int map[100][100][100];

    return map;

}

但是,我找不到 3d 數組的適當返回類型,它不會讓我像使用 2D 數組那樣使用 int*。

即使這樣的事情也不起作用:

int a[100][100][100];
int* b = a;

VS 似乎認為數據類型是int*(100)(100)但這沒有意義並且不起作用。

對於它的價值,我已經用谷歌搜索了這個並沒有看到任何解決方案。 謝謝

首先你應該

永遠不要返回指向局部非靜態變量的引用或指針。

現在來回答你的問題:

我想將它用作函數的返回類型,無論是作為指針還是類似的東西。但是我找不到 3d 數組的適當返回類型。

這(下面)是您如何為 3D 陣列執行此操作。 基本上有兩種方法可以解決這個問題:

方法一

//CreateCell is a function that returns a pointer to a 3D array of the size 100,100,100
int (*CreateCell())[100][100][100] {

    int map[100][100][100];

    return ↦
}

方法 1 可以在這里看到。

方法二

//CreateCell is a function that returns a pointer to a 3D array of the size 100,100,100
auto CreateCell() -> int(*)[100][100][100] {

    int map[100][100][100];

    return ↦
}

方法 2 使用尾隨返回類型並按此處所示工作

筆記

這兩種方法都返回一個指向必須避免的局部變量的指針。 我已經給出/寫了答案,以便您可以看到如何根據需要返回 3D 數組的指針。 您可以改為按值創建和返回 3D `std::vector`。

由於您想要 3D C 樣式數組,因此您需要有一個指向指針的指針,即int*** 此外,如果您使用這樣的創建函數,則需要分配內存。 否則,您將從該函數返回靜態分配的內存。

以下是如何執行此操作的快速示例:

#include <iostream>

static int*** create_cell() {    
    constexpr std::size_t n = 100;
    int*** map = new int**[n];
    for (std::size_t i = 0u; i < n; ++i) {
        map[i] = new int*[n];
        for (std::size_t j = 0u; j < n; ++j) {    
            map[i][j] = new int[n];
        }
    }   
    return map;
}

static void delete_cell(int***& map) { 
    constexpr std::size_t n = 100;
    for (std::size_t i = 0u; i < n; ++i) {
        for (std::size_t j = 0u; j < n; ++j) {    
            delete[] map[i][j];
        }
        delete[] map[i];
    }
    delete[] map;    
}

int main()
{
    int*** a = create_cell();

    a[0][0][0] = 1;
    std::cout << "a[0][0][0] = " << a[0][0][0] << std::endl;
    
    delete_cell(a);

    return 0;
}

這取決於您的用例:但是對於現代 C++,您可以使用stl容器(例如std::vectorstd::array來簡化您的生活。 在此處查看參考: std::arraystd::vector

例如,您可以定義 3D 類型:

#include <array>
#include <vector>
using vector_3d = std::vector<std::vector<std::vector<int>>>;
using array_3d = std::array<std::array<std::array<int, 100>, 100>, 100>;

然后將它們用作:

array_3d b;
b[0][0][0] = 1;
std::cout << "b[0][0][0] = " << b[0][0][0] << std::endl;

考慮在矩陣周圍使用一個簡單的包裝器:

struct Wrapper { int Mat[100][100][100] = {0}; };

然后簽名會變成這樣:

Wrapper *foo(...) { ... }

這是簡單的工作示例:

#include <iostream>
struct Wrapper { int Mat[100][100][100] = {0}; };
Wrapper *inc(Wrapper *w)
{
    for (int i=0;i<100;i++)
        for (int j=0;j<100;j++)
            for (int k=0;k<100;k++)
                w->Mat[i][j][k] += (i+j+k);
    return w;
}
int main(int argc, char **argv)
{
    Wrapper w;
    Wrapper *out = inc(&w);
    std::cout << out->Mat[5][6][7] << "\n";
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM