let's say I have a vector of string:
vector <string> words;
this vector contains the words: you are pretty
How can I convert these two words into a vector <char> characters;
I tried this:
vector <char> strToChar(words.begin(), words.end());
It doesn't work because it works only if words were std::string
and not a std::vector
Last edited on
I cooked this up real quick for you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
std::vector <std::string> words;
std::vector <char> strToChar;
words.push_back("Hello");
words.push_back("World");
for (int i = 0; i < words.size(); i++)
{
for (int j = 0; j < words[i].size(); j++)
{
strToChar.push_back(words[i][j]);
}
}
for (int i = 0; i < strToChar.size(); i++)
{
cout << strToChar[i];
}
return 0;
}
|
Last edited on
Perfect!!! you guys are the best.
Here's another way to do it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
#include <numeric>
#include <vector>
#include <string>
int main()
{
auto append = [](std::vector<char> v, const std::string& s)
{ v.insert(v.end(), s.begin(), s.end()); return v; };
std::vector<std::string> words{ "you", "are", "pretty" };
std::vector<char> chars = std::accumulate(words.begin(), words.end(), std::vector<char>(), append);
for (auto ch : chars)
std::cout << ch << '\n';
}
|
Last edited on