2015-09-26 30 views
0

我有两个向量。
一个是我怎样才能memcpy布尔向量字符数组?

std::vector<unsigned char> one_v; 

,另一个是

std::vector<bool> outputValuesInBits; 

我推值两者one_v和outputValuesInBits。
两个矢量都有两个字节。
one_v [0]和[1]被填充2字节的数据。
outputValuesInBits [0]到[15]用2字节的数据填充。
现在,我想复制(memcpy)数据到char数组。

我可以成功地从one_v向量复制数据,如下所示。

unsigned char* output = new unsigned char[one_v.size()](); 
memcpy(&output, one_v.data(), 2); 

但我无法从outputValuesInBits复制数据。
如果我做如下,

unsigned char* output = new unsigned char[outputValuesInBits.size()/8+1](); 
memcpy(&output, outputValuesInBits.data(), 2); 

它给了我一个错误

error: invalid use of void expression 
    memcpy(&output, outputValuesInBits.data(), 2); 

谁能告诉我如何我可以复制的布尔矢量字符数组?

预先感谢您!

+0

”存储不一定是一个布尔值数组,但库实现可以优化存储,以便每个值都存储在一个位中。“ - http://www.cplusplus.com/reference/vector/vector-bool/ - 重点是你不能依赖布局。 – sje397

回答

1

恐怕你不能以便携的方式。 Cplusplus page on vector说:专业化与非专业化的矢量具有相同的成员函数,但数据,emplace和emplace_back除外,这些专业化中不存在。这意味着data未定义在您尝试使用它时解释错误的原因。

如果可移植性是不是一种选择,就没有解决办法,因为存储不一定是布尔值的阵列,但库实现可以优化存储,使得每个值存储在一个单个位。(强调我的)。我对的理解可能是,您甚至不能确定16个布尔值是否存储在2个连续的字节中:实现只能为您提供一种方式来使用它们(几乎),就好像它们存储在16个不同的布尔值中一样。

如果你可以忘记partability,你必须找到从源头为您当前的实现要知道在哪里以及如何字节数组存储...但它不是那么容易......

+0

谢谢。然后,我可能不得不将位向量复制到位集。 'for循环'只是将数据复制到bitset的解决方案? –

+0

或者你认为有更好的方法从bool向量复制到char *? –

2

std::vector<bool>没有按”没有数据成员函数

+0

呃??? http://en.cppreference.com/w/cpp/container/vector/data –

+2

检查更好http://www.cplusplus.com/reference/vector/vector-bool/ – user5159806

+1

cppreference链接将是http:// en.cppreference.com/w/cpp/container/vector_bool – Cubbi

0

至少在g ++编译器中,可以使用vector :: iterator的_M_p成员,它是指向数据的指针。

实施例:

std::vector<bool> vBool(16, false); 
vBool[0] = true; 
vBool[2] = true; 
vBool[13] = true; 
std::vector<unsigned char> vChar(2); 
unsigned short *ptrUS = reinterpret_cast<unsigned short *>(&(vChar[0])); 
*ptrUS = *reinterpret_cast<unsigned short *>(vBool.begin()._M_p); 

std::cout << (unsigned int)vChar[0] << " " << (unsigned int)vChar[1] << "\n"; 

给出输出 '5 32',其对应于所述数字与第一和第三位(5)中,用第6位(32)。“