trying to initialize a string from a vector. I am supposed to get “hey” as the output. but I got “segmentation fault”. what did I do 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;
}
The vector class starts out with a size of zero (by default). So doing that will cause undefined behavior. (in your case, a segmentation fault)
You should use
push_back()instead:This will append each
charto the vector.