日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

C++的std::vector<bool>轉(zhuǎn)儲(chǔ)文件問(wèn)題_C 語(yǔ)言

作者:qq_42766764 ? 更新時(shí)間: 2022-12-10 編程語(yǔ)言

前言

總所周知,C++的std::vector<bool>并不是一種“標(biāo)準(zhǔn)”的容器。

該容器按位存儲(chǔ)數(shù)據(jù),使用at(size_t)或者其重載的operator[](size_t)返回的都是一個(gè)特化的Reference類,使用begin()之類的函數(shù)也是特殊的迭代器。

而且不同的編譯器,其標(biāo)準(zhǔn)庫(kù)的實(shí)現(xiàn)方式也不一樣。如此,直接將數(shù)據(jù)std::vector<bool>轉(zhuǎn)儲(chǔ)到文件似乎就顯得不可能了。

那么是否有方法可以進(jìn)行轉(zhuǎn)儲(chǔ)呢?答案是有的,只要能找到存儲(chǔ)數(shù)據(jù)的起始指針即可將數(shù)據(jù)轉(zhuǎn)儲(chǔ)。

獲取數(shù)據(jù)源地址

MSVC

1、微軟沒有實(shí)現(xiàn)data()函數(shù)的接口。

2、微軟直接暴露(public)了存儲(chǔ)std::vector<bool>的std::vector<unsigned int>。

3、微軟的迭代器直接暴露(public)了迭代器指向的數(shù)據(jù)指針。

GCC

1、GCC偏特化實(shí)現(xiàn)了data()函數(shù)接口,但返回是void。

2、GCC提供了訪問(wèn)直接存儲(chǔ)數(shù)據(jù)的一個(gè)結(jié)構(gòu)化表述類的接口,但真的很不優(yōu)雅。

3、GCC的迭代器同樣直接暴露了迭代器指向的數(shù)據(jù)指針。

數(shù)據(jù)地址獲取方法

auto GetBoolVectorStartAddress(std::vector<bool>& vec) {
#ifdef __GNUC__
	/*方法一
	auto begin = vec.begin();
	return begin._M_p;
	*/

	//方法二
	auto Impl = vec._M_get_Bit_allocator(); //獲取_Bvector_impl類型的_M_impl;
	return Impl._M_start._M_p; //Impl._M_start就是begin返回的迭代器
#else
	/*方法一
	auto& source = vec._Myvec;
	return &source[0];*/

	//方法二
	auto begin = vec.begin();
	return begin._Myptr;
#endif
}

#include<fstream>

int mian(){
	std::vector<bool> test;
	for(int i = 0; i < 65536; i++)
	{
		test.push_back(i % 2 ? true : false);
	}
	auto StartAddress = GetBoolVectorStartAddress(test);
	std::ofstream ofs("test.bin", std::ios::binary|std::ios::out);
	ofs.write((char*)StartAddress, 8192);
	ofs.close();
	return 0;
}

結(jié)果

總結(jié)

將std::vector<bool>轉(zhuǎn)儲(chǔ)文件的方法很簡(jiǎn)單,只要找到相應(yīng)的起始位置的指針,在將數(shù)據(jù)直接使用流輸出即可。

原文鏈接:https://blog.csdn.net/qq_42766764/article/details/126526771

欄目分類
最近更新