簡體   English   中英

制作第二維是常數的動態二維數組是愚蠢的嗎?

[英]Is it dumb to make a dynamic 2d array where the second dimension is a constant?

我正在嘗試創建一個行數可變的數組,但它總是有 4 列。 正在做類似的事情:

int** numGrades = new int* [num_exams];
for (int i = 0; i < num_exams; ++i)
{
    numGrades[i] = new int[4];
}

這樣做的好方法嗎? 我覺得有一種更簡單的方法,但我想不出一個。 此外,該數組不斷給我內存泄漏,所以我想知道這是否是因為我在做我不應該做的事情。 僅供參考,該程序禁止使用載體。

你可以制作一個行數組。

struct Row{
   int values[4];
};

Row* numGrades = new Row[num_exams];

您可以跳過 for 循環:

int* numGrades = new int[num_exams*4];
int firstElement = numGrades[x];
int secondElement = numGrades[x+1];
int thirdElement = numGrades[x+2];
int fourthElement = numGrades[x+3];

通過跳過 for 循環,您可以獲得:

  1. 您不必使用 for 循環來釋放內存:

    刪除[] numGrades;

  2. 堆沒有那么多碎片,因為您不會多次調用“新”。

但這一切都取決於您使用它的目的。 在現代 C++ 中,使用動態但在 std::vector 中創建結構並不是一個好主意。

也許你可以試試這個。

typedef int row[4];
//or
using row = int[4];

row *numGrades = new row[num_exams];

在許多情況下,分配一定數量的固定大小的數組是好的和有利的。

除了struct (這是一個很好的選擇)之外,另一種選擇是聲明一個包含固定數量元素的Pointer-To-Array 這樣做的好處是您可以為內存塊提供單一分配單一空閑 (就像使用struct 數組一樣)如果您需要增加內存塊(使用 -- 聲明更大的塊,將現有復制到更大,刪除現有重新分配),它會簡化過程。 在你的情況下:

 int (*numGrades)[4] = new int[num_exams][4];

這將一次分配num_exams數量的 4 個int數組。 這提供了單個delete[] numGrades; 當你完成記憶時。

使用std::istringstream保存示例值以讀取到包含修復大小數組的內存塊的簡短示例可能是:

#include <iostream>
#include <sstream>

int main (void) {
    
    std::istringstream iss { "1 2 3 4 5 6 7 8 9" };
    
    int npoints = 3,
        (*points)[3] = new int[npoints][3],
        n = 0;
    
    while (n < 3 && iss >> points[n][0] >> points[n][1] >> points[n][2])
        n++;
    
    for (int i = 0; i < n; i++)
        std::cout << points[i][0] << "  " << points[i][1] << "  " << points[i][2] << '\n';
    
    delete[] points;
}

注意:如果不是出於教育目的,您應該避免使用newdelete來支持諸如std::vector之類的容器)

示例使用/輸出

$ ./bin/newptr2array3
1  2  3
4  5  6
7  8  9

值得注意的是, struct的好處是它允許您使用std::istreamstd::ostream重載>><<以提供方便的函數來讀取和寫入您需要的數據。

所以無論哪種方式,一個指針到陣列固定元件,或創建一個struct ,然后數組struct是完全沒有問題。

暫無
暫無

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

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