简体   繁体   English

何时使用std :: vector <unsigned char>与std :: vector <char>

[英]When to use std::vector<unsigned char> vs. std::vector<char>

Which of one of these is best suited for managing a character buffer that can be easily converted to std::string and passed to and used ( ie read / write ) in C functions 其中一个最适合管理一个字符缓冲区,该缓冲区可以很容易地转换为std :: string并传递给C函数并使用(即读/写)

std::vector<unsigned char> 
std::vector<char>

char 's signedness depends on the compiler. char的签名取决于编译器。 1 1

It can represent a unsigned char or signed char . 它可以表示unsigned charsigned char Which type is used when representing a string is dependent on the compiler - therefore you should use char for portability, and clarity. 表示string时使用的类型取决于编译器 - 因此您应该使用char来实现可移植性和清晰度。 If that isn't enough, would the less typing needed when writing char convince you? 如果这还不够,那么写char时所需的打字就越少说服你吗? :) :)

Again, the compiler thinks string s are of type char * , which can be equivalent to unsigned char * or signed char * . 同样,编译器认为string s的类型为char * ,它可以等同于unsigned char *signed char * If you're going to be working with string s use std::vector<char> . 如果您要使用string s,请使用std::vector<char>

1 char is the only type with this behavior. 1 char是唯一具有此行为的类型。


References 参考

1 Is char signed or unsigned by default? 1 默认情况下是char签名还是未签名?

char is more compatible with strings than unsigned char . charunsigned char字符串更兼容。 String literals are char[] and std::string is actually std::basic_string<char> . 字符串文字是char[]std::string实际上是std::basic_string<char>

Both are equally well suited. 两者都同样适合。 If these are character buffers, as opposed to bytes, I would go with std::vector< char >. 如果这些是字符缓冲区,而不是字节,我会使用std :: vector <char>。

You can create a string from a vector of any of those types with std::string( v.begin(), b.end() ); 您可以使用std :: string(v.begin(),b.end())从任何类型的向量创建一个字符串;

char , unsigned char , and signed char are 3 distinct types. charunsigned charsigned char是3种不同的类型。

  • Use an unsigned char or a signed char when dealing with numbers. 在处理数字时使用unsigned charsigned char
  • Use a regular char when dealing with strings. 处理字符串时使用常规char

Thus, you should use a char . 因此,您应该使用char

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM