#Easiest way to convert a string to a vector of letters?
15 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.
what's the error
oh because word[i] is a char
not std::string, so change the return type to std::vector<char>
You can use a range based for loop for this
for (const char l : word)
ret.push_back(l);
or another method using <algorithm> header
// Assuming you allocated enough space in ret already
std::copy(word.begin(), word.end(), ret);
The second version is
C++ code
Sounds a bit like an XY problem, maybe just construct a string when you need it like std::string(1, word[n]);
std::vector<char> to_vector(const std::string& word){
return std::vector<char>(word.begin(), word.end());
}
there is no good reason for you to need a vector of strings, each element of a string is a char, so you get a vector of char
if you really want them, then do the conversions manually
std::vector<std::string> to_vector(const std::string& word){
std::vector<std::string> ret;
ret.reserve(word.size());
for (int i=0;i<word.length();i++){
ret.push_back(std::string(word[i]));
}
return ret
}
!solved