各種コンテナのファイル出力に関して

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

各種コンテナのファイル出力に関して

#1

投稿記事 by 赤鬼 » 13年前

各種コンテナのファイル出力に関して。
C++の仕様書が読んで調べてからと思ったのですが、JISCの方がエラーで見れなくなってるので質問させていただきました。
コンテナをそのまま書き出す事が出来ませんので(やり方がわからないだけであるのかも?)
要素を書き込むのですが、vector内部で配列がどう扱われている分かりません。
下記の例では成功しましたが、アドレスを取って書き込む場合値は保障されるのでしょうか?

コード:

void main(){
	vector<int> a(3.0);
	a[0]=10;
	a[1]=11;
	a[2]=12;
	fstream fs("a.bin",ios::out|ios::binary|ios::trunc);			//ファイルストリーム
	fs.write((char*)&a[0],sizeof(a[0])*a.size());
	fs.close();

	a[0]=0;
	a[1]=0;
	a[2]=0;

	fs.open("a.bin",ios::in|ios::binary);
	fs.read((char*)&a[0],sizeof(a[0])*a.size());
	cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;	//
}

結果
10 11 12
また、保障されないのであればイテレータを取って書き込む方が普通なのでしょうか?

コード:

void main(){
	vector<int> a(3.0);
	a[0]=10;
	a[1]=11;
	a[2]=12;
	
	fstream fs("a.bin",ios::out|ios::binary|ios::trunc);			//ファイルストリーム
	vector<int>::iterator it;
	for(it=a.begin();it!=a.end();it++)
		fs.write((char*)&*it,sizeof(a[0]));
	fs.close();
	
	a[0]=0;
	a[1]=0;
	a[2]=0;
	
	fs.open("a.bin",ios::in|ios::binary);
	
	for(it=a.begin();it!=a.end();it++)
		fs.read((char*)&*it,sizeof(a[0]));

	cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;	//
}

結果
10 11 12

かずま

Re: 各種コンテナのファイル出力に関して

#2

投稿記事 by かずま » 13年前

赤鬼 さんが書きました:下記の例では成功しましたが、アドレスを取って書き込む場合値は保障されるのでしょうか?
保証されます。
正式な規格書でなくて、ドラフトですが、まあ問題ないでしょう。

コード:

Document Number: N3242=11-0012
Date: 2011-02-28
Revises: N3225
Reply to: Pete Becker
Roundhouse Consulting, Ltd.
\pete@versatilecoding.com
Working Draft, Standard for Programming
Language C++
Note: this is an early draft. It’s known to be incomplet and incorrekt,
and it has lots of bad formatting.

23.3.6 Class template vector                                    [vector]
23.3.6.1 Class template vector overview                [vector.overview]

A vector is a sequence container that supports random access iterators.
In addition, it supports (amortized) constant time insert and erase
operations at the end; insert and erase in the middle take linear time.
Storage management is handled automatically, though hints can be given
to improve efficiency. The elements of a vector are stored contiguously,
meaning that if v is a vector<T, Allocator> where T is some type other
than bool, then it obeys the identity
&v[n] == &v[0] + n for all 0 <= n < v.size().

赤鬼

Re: 各種コンテナのファイル出力に関して

#3

投稿記事 by 赤鬼 » 13年前

vector are stored contiguously.
なるほど、要素は近接して格納されますって書いてありますね。
有難うございました。

閉鎖

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