Vector of string to Vector of Char

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
One way to do it:
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
30
#include <iostream>
#include <vector>
#include <stdlib.h>

using namespace std;

int main()
{
  vector <string> words;
  words.push_back("You");
  words.push_back("are");
  words.push_back("pretty");

  vector<char> chars;

  for (size_t i = 0; i < words.size(); i++)
  {
    string s = words.at(i);
    for (size_t j = 0; j < s.length(); j++)
      chars.push_back(s[j]);
  }

  for (size_t i = 0; i < chars.size(); i++)
  {
    cout << chars[i];
  }
  cout << "\n\n";
system("pause");
}
Perfect!!! you guys are the best.
Something like this perhaps?

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
30
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <cctype>

std::vector<char> to_vect_char(std::string& sentence)
{
    std::vector<std::string> words;
    std::stringstream sin(sentence);
    std::string word;
    while(sin >> word)
        words.push_back(word);
    std::vector<char> chars;
    for(auto& itr : words)
        std::copy(itr.begin(), itr.end(), std::back_inserter(chars));
    return(chars);
}


int main()
{
    std::string s = "Hello World";

    std::vector<char> words_as_chars = to_vect_char(s);
    for(auto& itr : words_as_chars)
        std::cout << itr << ' ';

    return 0;
}


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
Topic archived. No new replies allowed.