[英]How to fill array of struct containing pointer arrays
我在C ++中有一個小而非常簡單的問題。 我想填充包含雙精度數組的結構數組。 我怎樣才能做到這一點?
typedef struct
{
double *inputs[2];
double *target[1];
} Data;
Data data[]
{
new double[2]{10, 20}, new double[1]{30},
new double[2]{40, 50}, new double[1]{60},
new double[2]{70, 80}, new double[1]{90},
new double[2]{100, 110}, new double[1]{120}
};
並在main()
printf("data[0]: inputs: %f %f, targets: %f\n",
*data[0].inputs[0],
*data[0].inputs[1],
*data[0].target[0]);
這是我的想法,但是當我運行它時,它將打印此內容:
data[0]: inputs: 10.000000 30.000000, targets: 40.000000
當然,在數組數據的末尾(如第3項或第4項),將導致UNAUTHORIZED ACCESS TO MEMORY
謝謝您的想法和耐心;)
使用現代c ++可使您的代碼更加簡單和安全:
#include <iostream>
#include <array>
#include <vector>
struct Data {
std::array<double,2> inputs;
std::array<double,1> target;
};
int main()
{
std::vector<Data> data = {
{ {10, 20}, {30} },
{ {40, 50}, {60} },
{ {70, 80}, {90} },
{ {100, 110}, {120} }
};
std::cout << "data[0]: inputs: " << data[0].inputs[0] << " " << data[0].inputs[1] << ", targets: " << data[0].target[0] << "\n";
}
您的原始問題是double *inputs[2]
聲明指針的2元件陣列double
不是指針到的2元件陣列doubles
。
您的Data
結構包含2個字段,2個double
指針數組和1個double
指針數組。
這意味着,初始化需要最多3個double
指針,這意味着初始化中的代碼看起來像這樣
Data data[]{
{new double[2]{ 10, 20 }, new double[1]{ 30 }, new double[2]{ 40, 50 }}, //1st object
{new double[1]{ 60 }, new double[2]{ 70, 80 }, new double[1]{ 90 }}, //2nd object
{new double[2]{ 100, 110 }, new double[1]{ 120 }} //3rd object but 2 parameters??
};
嘗試循環打印時,第3個對象將導致段錯誤,因為尚未正確初始化target
字段(使用Visual Studio進行調試時,將其設置為null,不確定其他編譯器)。
您的問題在這里:
typedef struct {
double *inputs[2]; // this
double *target[1]; // this
} Data;
這是一個指針數組,希望能在動態1D數組中起作用。 簡單的解決方法是:
struct Data {
double *inputs = nullptr;
double *target = nullptr;
} ;
但是,您使用new
分配了很多堆內存,這使delete
任務變得很繁瑣,因此很難管理數據結構。 我強烈建議您使用std::vector<>
,這會使您的任務更輕松,更整潔。
#include <vector>
#include <iostream>
struct Data
{
std::vector<double> inputs; // use instead of double *inputs[2];
std::vector<double> target; // use instead of double *target[1];
//Data(const std::vector<double>& a, const std::vector<double>& b) :inputs(a), target(b){}
};
int main()
{
std::vector<Data> data = // now in your main structure array
{ { {10, 20}, {30} },
{ {40, 50}, {60} },
{ {70, 80}, {90} },
{ {100, 110},{120} }
};
// access using range based loop now
for(const Data& each_strcut: data)
std::cout << each_strcut.inputs[0] << " " << each_strcut.inputs[1]
<<"\t" << each_strcut.target[0] << std::endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.