How to initialize a vector with characters of a string in C++

2 Answers

0 votes
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
  
int main()
{
    std::string s = "c++ programming";
  
    std::vector<char> vec(s.begin(), s.end());
  
    copy(vec.cbegin(), vec.cend(), std::ostream_iterator<char>(std::cout, " "));
}


 
/*
run:
 
c + +   p r o g r a m m i n g 
 
*/

 



answered Mar 1, 2018 by avibootz
edited Nov 24, 2025 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::string s = "c++ programming";

    std::vector<char> vec(s.begin(), s.end());

    for (char ch : vec) {
        std::cout << ch << ' ';
    }
}


 
/*
run:
 
c + +   p r o g r a m m i n g 
 
*/

 



answered Nov 24, 2025 by avibootz
...