I am using a library which accepts data as a vector of chars. I need to pass a string to the library.
I think about using std::vector constructor which accepts iterators to carry out the conversion – but wondered if there is a better way of doing it?
/*Note: json_str is of type std::string*/
const std::vector<char> charvect(json_str.begin(), json_str.end());
Nope, that’s the way to do it, directly initializing the vector with the data from the string.
As @ildjarn points out in his comment, if for whatever reason your data buffer needs to be null-terminated, you need to explicitly add it with
charvect.push_back('\0').Also note, if you want to reuse the buffer, use the
assignmember function which takes iterators.