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:
vector<char> cvec;
cvec.push_back('h');
cvec.push_back('e');
cvec.push_back('y');
This will append each char
to the vector.
You need to allocate space in the vector, like this:
vector<char> cvec(3);
Or push the characters in one by one:
vector<char> cvec;
cvec.push_back('h');
cvec.push_back('e');
cvec.push_back('y');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With