ページ 11

構造体の配列を動的に確保したい

Posted: 2015年8月30日(日) 12:14
by kanse_00
これまで構造体を使っていたのですが、下記のように構造体tの配列の要素数をt[10000]みたいに初めに決めてい

ました。

コード:

typedef struct {
	int day;int time;
	int buy_ita[8]; int sell_ita[8];
	int buy_price[8]; int sell_price[8];
	int ryou; int price;
	int limit_delta_buy[8], limit_delta_price_buy[8];
	int limit_delta_sell[8], limit_delta_price_sell[8];
	int delta_price;
	int trading_volume;
}Ita;
Ita t[10000];
これを動的に決定したいと思い、C++のvectorで書いてみたのですが、
例外がスローされました。
書き込み中にアクセス違反が発生しました。
と出てしまいました。
やりたいのは、株式データの処理なのですが、データの数はその日ごとにわからない。
各時点で様々な情報(売/買の板の値段・量,その時点までの売買高など)

コード:

#include <iostream>
#include <vector>
#include <string>
#include <random>

#include <algorithm>
using namespace std;

typedef struct {
	int day;int time;
	int buy_ita[8]; int sell_ita[8];
	int buy_price[8]; int sell_price[8];
	int ryou; int price;
	int limit_delta_buy[8], limit_delta_price_buy[8];
	int limit_delta_sell[8], limit_delta_price_sell[8];
	int delta_price;
	int trading_volume;
}Ita;

int main()
{
vector<Ita> t;

//test
t[0].time = 900;
cout<<t[0].time<<endl;

return 0;
}

Re: 構造体の配列を動的に確保したい

Posted: 2015年8月30日(日) 12:56
by みけCAT
要素にアクセスする前に、push_backやresize、コンストラクタなどで領域(要素)を確保しないといけません。
vector - C++ Reference

実装例

コード:

#include <iostream>
#include <vector>
#include <string>
#include <random>

#include <algorithm>
using namespace std;

typedef struct {
	int day;int time;
	int buy_ita[8]; int sell_ita[8];
	int buy_price[8]; int sell_price[8];
	int ryou; int price;
	int limit_delta_buy[8], limit_delta_price_buy[8];
	int limit_delta_sell[8], limit_delta_price_sell[8];
	int delta_price;
	int trading_volume;
}Ita;

int main()
{
vector<Ita> t;

t.push_back(Ita()); // add

//test
t[0].time = 900;
cout<<t[0].time<<endl;

return 0;
}

Re: 構造体の配列を動的に確保したい

Posted: 2015年8月30日(日) 18:47
by kanse
ありがとうございます。

Re: 構造体の配列を動的に確保したい

Posted: 2015年8月30日(日) 20:30
by みけCAT
kanse さんが書きました:ありがとうございます。
解決したのでしたら、解決チェックをお願いします。
投稿画面の「送信」ボタンの右にある「解決!」にチェックを入れた状態で返信をしてください。

Re: 構造体の配列を動的に確保したい

Posted: 2015年8月30日(日) 23:08
by kanse
ありがとうございました。
解決チェック、了解しました。