如何将vector<unsigned long> v;
转换为char buffer[sizeof(unsigned long)*v.size()]
;反之亦然。
我试过
std::copy(b.begin(), b.end(), buffer);
和v.insert()
但结果不明确。任何人都可以建议如何做到这一点。
答案 0 :(得分:0)
如果您只需要将数据传递给某个需要char *
的库函数assert(v.size());
char *p = (char*) &v[0];
否则这里有一些示例代码从std :: vector和char *来回复制数据,虽然我建议坚持使用一个接口,除非你有理由这样做。
#include <iostream>
#include <vector>
#include <memory>
#include <assert.h>
int main()
{
size_t count = 20;
std::vector<unsigned int> v;
v.resize(count);
assert(v.size());
// make a vector with the numbers 1 through count
for (size_t index = 0; index < count; ++index)
v[index] = index + 1;
// make a buffer of char[] (using unique_ptr to handle cleanup)
std::unique_ptr<char> buffer(new char[v.size() * sizeof(v[0])]);
// copy from v into a buffer of char[]
memcpy(buffer.get(), &v[0], v.size() * sizeof(v[0]));
// next we get rid of v, and copy the elements back in from the char buffer
v.clear();
// now suppose we have a char array of count unsigned ints (which we do)
// (the count better be right)
// just say it's an unsigned int* and you get pointer arithmetic for unsigned int
unsigned int * pInt = reinterpret_cast<unsigned int*>(buffer.get());
for (size_t index = 0; index < count; ++index)
v.push_back(*pInt++);
// print out as proof
for (auto &x : v)
std::cout << x << " ";
return 0;
}
答案 1 :(得分:-1)
例如,您可以尝试以下方法
#include <iostream>
#include <vector>
#include <cstring>
#include <numeric>
int main()
{
std::vector<unsigned long> v = { 1, 2, 3 };
char *p = new char[sizeof( unsigned long ) * v.size()];
std::accumulate( v.begin(), v.end(), p,
[]( char *p, unsigned long x)
{
return memcpy( p, &x, sizeof( x ) ), p + sizeof( x );
} );
std::vector<unsigned long> v2( v.size() );
char *q = p;
for ( auto &x : v2 )
{
memcpy( &x, q, sizeof( x ) );
q += sizeof( x );
}
for ( auto x : v2 ) std::cout << x << ' ';
std::cout << std::endl;
delete []p;
return 0;
}
输出
1 2 3
lambda表达式中的return语句也可以像
一样编写return ( char * )memcpy( p, &x, sizeof( x ) ) + sizeof( x );
或者你确实可以通过以下方式在字符缓冲区中复制整个矢量
std::memcpy( p, v.data(), v.size() * sizeof( unsigned long ) );
例如
#include <iostream>
#include <cstring>
#include <vector>
int main()
{
std::vector<unsigned long> v = { 1, 2, 3 };
char *p = new char[sizeof( unsigned long ) * v.size()];
memcpy( p, v.data(), v.size() * sizeof( unsigned long ) );
std::vector<unsigned long> v2( v.size() );
char *q = p;
for ( auto &x : v2 )
{
memcpy( &x, q, sizeof( x ) );
q += sizeof( x );
}
for ( auto x : v2 ) std::cout << x << ' ';
std::cout << std::endl;
delete []p;
return 0;
}
而不是这个循环
char *q = p;
for ( auto &x : v2 )
{
memcpy( &x, q, sizeof( x ) );
q += sizeof( x );
}
你也可以使用memcpy。例如
memcpy( v2.data(), p, v2.size() * sizeof( unsigned long ) );