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

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
kanse_00

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

#1

投稿記事 by kanse_00 » 10年前

これまで構造体を使っていたのですが、下記のように構造体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;
}

アバター
みけCAT
記事: 6734
登録日時: 14年前
住所: 千葉県
連絡を取る:

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

#2

投稿記事 by みけCAT » 10年前

要素にアクセスする前に、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;
}
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

kanse
記事: 6
登録日時: 10年前

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

#3

投稿記事 by kanse » 10年前

ありがとうございます。

アバター
みけCAT
記事: 6734
登録日時: 14年前
住所: 千葉県
連絡を取る:

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

#4

投稿記事 by みけCAT » 10年前

kanse さんが書きました:ありがとうございます。
解決したのでしたら、解決チェックをお願いします。
投稿画面の「送信」ボタンの右にある「解決!」にチェックを入れた状態で返信をしてください。
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

kanse
記事: 6
登録日時: 10年前

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

#5

投稿記事 by kanse » 10年前

ありがとうございました。
解決チェック、了解しました。

閉鎖

“C言語何でも質問掲示板” へ戻る