Originally Posted by
appointment
I am trying to insert a new element into a vector in C++ under Ubuntu Linux.
The following is what I did, where v contain some element already. InsertElementNo is the element number the new content "entry" should be inserted.
For example:
v contains "Test,Is,Good"
If entry = "Lord" and InsertElementNo = 2,
After v.insert v should look like "Test,Lord,Is,Good"
Code:
vector <string> v;
vector <string>::iterator pos = v.begin();
.......
v.insert(pos+(InsertElementNo-1), entry);
However the above code gives me "segmentation error".
Couldn't figure out why.
How about this?
Code:
void do_insertion( vector<string>& v, const string& s, const unsigned int pos )
{
vector<string> buff;
buffer.reserve( v.size()+1 );
copy( v.begin(), v.begin()+pos, back_inserter(buff) );
buff.push_back( s );
copy( v.begin()+pos, v.end(), back_inserter(buff) );
v.swap( buff);
}