Vector <char> to segment segmentation error

trying to initialize a string from a vector. I have to get "hey" as a result. but I got a "segmentation fault". What have I done wrong?

//write a program that initializes a string from a vector<char> #include <iostream> #include <vector> #include <string> using namespace std; int main () { vector<char> cvec; cvec[0]='h'; cvec[1]='e'; cvec[2]='y'; string s(cvec.begin(),cvec.end()); cout<<s<<endl; return 0; } 
+6
source share
2 answers

The vector class starts from scratch (by default). Thus, this will lead to undefined behavior. (in your case, a segmentation error)

Instead, use push_back() :

 vector<char> cvec; cvec.push_back('h'); cvec.push_back('e'); cvec.push_back('y'); 

This will add each char to the vector.

+21
source

You need to select a place in the vector, for example:

 vector<char> cvec(3); 

Or tap the characters one by one:

 vector<char> cvec; cvec.push_back('h'); cvec.push_back('e'); cvec.push_back('y'); 
+11
source

Source: https://habr.com/ru/post/901268/


All Articles