Say, I have a string and a vector of bools. Based on the characters in the string, I want to set the corresponding vector indices to true.
std::vector<bool> is_present(256, false);
for (int i = 0; i < str.size(); ++i)
{
is_present[str[i]] = true;
}
From what I understand, the standard does not define the signed-ness of a char. Depending on the platform, it may be signed or unsigned. On most platforms, signed char will be an 8-bit two’s complement number (-128 to 127), and unsigned char will be an 8-bit unsigned integer (0 to 255).
If that is the case, is there a possibility that str[i] will return a negative number and cause a memory fault in is_present[str[i]]? or is the char getting typecast to vector<bool>::size_type which is unsigned and hence no problems can occur?
Also, is it better to use vector<bool> is_present(pow(2, CHAR_BIT)), false) instead of hardcoding it to 256?
Always cast a
charto anunsigned charif you want to be definite about the values.You can say
1u << CHAR_BITto get the desired size.