Tom
Tom

Reputation: 183

How to convert std:wstring to std::vector<wchar_t>

If

std::wstring word = L"xxxxxxx";

Then how to do the following conversion?

std::vector<wchar_t> chars = word;

Upvotes: 1

Views: 2726

Answers (2)

krzaq
krzaq

Reputation: 16421

Just initialize it with a pair of iterators:

std::vector<wchar_t> chars(word.begin(), word.end());

The above will not add the null terminator (but if the string contains one, it will be copied). If you want it, initialize the vector with a pair of pointers to the underlying string data instead:

std::vector<wchar_t> chars(word.c_str(), word.c_str() + word.size() + 1);

Remember to add 1 for the null terminator, otherwise the effect will be the same as in the first example.

Upvotes: 3

CashCow
CashCow

Reputation: 31445

There is a way to create it in one go including the null terminator by using the c_str() or data() from the wstring. (In C++11 these are both guaranteed to be null terminated), and then adding size()+1 for the end position, also guaranteed to be well-defined behaviour.

Thus:

std::vector<wchar_t> chars( word.c_str(), word.c_str() + word.size() + 1 );

(or use data() instead of c_str() but only C++11 onward )

Upvotes: 1

Related Questions