#Easiest way to convert a string to a vector of letters?

15 messages · Page 1 of 1 (latest)

green abyss
#
    std::vector<std::string> ret;
    for (int i=0;i<word.length();i++){
        ret.push_back(word[i]);
    }
}```
The code above gives me an error. I assume the issue arrises because *word[i]* is not a string?
feral sealBOT
#

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.

hardy kindle
#

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 peepohappy C++ code

pine radish
#

Sounds a bit like an XY problem, maybe just construct a string when you need it like std::string(1, word[n]);

sweet wolf
#

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
}
green abyss
#

!solved