簡體   English   中英

如何在不知道其大小的情況下初始化容器結構?

[英]How to initialize a container struct without knowing its size?

我是 C++ 的業余愛好者,我正在研究科學計算代碼。 我定義了一個結構來存儲從文件輸入的所有數據。 在結構中,我有幾個二維和一維數組,其維度取決於數據輸入,因此我需要根據數據輸入動態定義結構。 如何在 C++ 中實現這一目標? 謝謝大家的幫助!

有幾種方法可以完成此操作,具體取決於您解析輸入卡組的方式。 最簡單的方法是通過std::vectors ,它是標准模板庫的一部分。 這些使用動態內存並將在堆上分配。 您可以執行以下操作:

// simple prototype of your struct
struct input_data{
  std::vector<double> one_d_data;
  std::vector<std::vector<double>> two_d_data;
};

// ad-hoc example of parsing and adding data to the 1d data container
while(still_parsing){
  double value = parser.get_next_1d_value();
  input_data.one_d_data.push_back(value);
}

2d 案例實際上取決於您對數據的了解程度。 如果您知道所有條目都是標准的 3 分量向量或 9 分量張量,那么您可以預先分配它們。

無論哪種方式,聽起來您都應該閱讀有關std::vector並確定設計的最佳前進路徑。

暫無
暫無

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

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