Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

c++ - Converting std::string to std::vector<char>

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()); 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('').

Also note, if you want to reuse the buffer, use the assign member function which takes iterators.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...