Fastest way to convert vector of chars to a string

6.1k views Asked by At

I have a vector of chars (actually unsigned chars):

std::vector<unsigned char> vec;

I would like to cast it/ copy it to a string object. I have tried to do this in the following way:

std::string requestedName;

for (auto letter : vec)
{
    requestedName.append((char)letter);
}

But compiller says that such conversion is not possible. I would aprichiate all help.

1

There are 1 answers

3
Cory Kramer On

You can use the operator += to perform this concatenation

std::vector<unsigned char> vec {'a', 'b', 'c', 'd'};
std::string requestedName;
for (auto letter : vec)
    requestedName += letter;

Working demo

Also instead of concatenating in a loop, you can use the following overload of the std::string constructor

std::vector<unsigned char> vec {'a', 'b', 'c', 'd'};
std::string requestedName{ vec.begin(), vec.end() };