哪个是用于保存和访问二进制数据的更好的c ++容器?
std::vector<unsigned char>
Run Code Online (Sandbox Code Playgroud)
要么
std::string
Run Code Online (Sandbox Code Playgroud)
一个比另一个更有效吗?
一个更"正确"的用法吗?
我的问题与此相似,但有点具体.我正在编写一个函数来读取使用little endian表示的istream中的32位无符号整数.在C这样的东西会起作用:
#include <stdio.h>
#include <inttypes.h>
uint_least32_t foo(FILE* file)
{
unsigned char buffer[4];
fread(buffer, sizeof(buffer), 1, file);
uint_least32_t ret = buffer[0];
ret |= (uint_least32_t) buffer[1] << 8;
ret |= (uint_least32_t) buffer[2] << 16;
ret |= (uint_least32_t) buffer[3] << 24;
return ret;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试使用一个类似的东西,istream
我遇到了我认为是未定义的行为
uint_least32_t bar(istream& file)
{
char buffer[4];
file.read(buffer, sizeof(buffer));
// The casts to unsigned char are to prevent sign extension on systems where
// char is signed.
uint_least32_t ret = (unsigned char) buffer[0];
ret …
Run Code Online (Sandbox Code Playgroud) 是否有任何STL容器似乎非常适合用作数据库软件的BLOB?我会想vector<char>
,但是还有更好的东西吗?也许是std::string
?还是一些非STL容器?
我想知道是否有必要在下面的函数中重新解释.ITER_T可能是char*,unsigned char*,std :: vector <unsigned char> iterator,或类似的东西.到目前为止它似乎没有受到伤害,但是铸造是否会影响字节的复制方式?
template<class ITER_T>
char *copy_binary(
unsigned char length,
const ITER_T& begin)
{
// alloc_storage() returns a char*
unsigned char* stg = reinterpret_cast<unsigned char*>(alloc_storage(length));
std::copy(begin, begin + length, stg);
return reinterpret_cast<char*>(stg);
}
Run Code Online (Sandbox Code Playgroud) 有没有办法强制字符串使用unsigned char而不是char?也许在构造函数中?
我需要进行算术运算(主要是递增,递减,〜(按位NOT)),我需要能够使用溢出255 ++ == 0 ...不是127 ++ == -128(和下溢0- - == 255 ...)
我不确定问题是否有意义,在这里说一下这是一个很好的问题(流)为什么C++流使用char而不是unsigned char?
我没有尝试将字符串转换为unsigned char我发现很多问题如何在两者之间进行转换.