Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stdvector

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 ( i.e. read / write ) in C functions

std::vector<unsigned char> 
std::vector<char>
like image 921
karimjee Avatar asked Jul 29 '26 09:07

karimjee


2 Answers

char's signedness depends on the compiler.1

It can represent a unsigned char or signed char. Which type is used when representing a string is dependent on the compiler - therefore you should use char for portability, and clarity. If that isn't enough, would the less typing needed when writing char convince you? :)

Again, the compiler thinks strings are of type char *, which can be equivalent to unsigned char * or signed char *. If you're going to be working with strings use std::vector<char>.

1 char is the only type with this behavior.


References

1 Is char signed or unsigned by default?

like image 168
Mateen Ulhaq Avatar answered Jul 31 '26 22:07

Mateen Ulhaq


char is more compatible with strings than unsigned char. String literals are char[] and std::string is actually std::basic_string<char>.

like image 25
Mark Ransom Avatar answered Jul 31 '26 22:07

Mark Ransom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!