Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ insert into vector at known position

I wish to insert into a c++ vector at a known position. I know the c++ library has an insert() function that takes a position and the object to insert but the position type is an iterator. I wish to insert into the vector like I would insert into an array, using a specific index.

like image 208
myx Avatar asked Feb 24 '10 23:02

myx


People also ask

How do you insert vector in position?

Inserting a single element at specific position in vectoriterator insert (const_iterator pos, const value_type& val); iterator insert (const_iterator pos, const value_type& val); It Inserts a copy of give element “val”, before the iterator position “pos” and also returns the iterator pointing to new inserted element.

Can we insert an element in between a vector in C++?

Using the insert() Function on Vectors. The insert() method can be used to insert single or multiple elements into a given vector in different ways, for different cases.

How do you add values to a vector?

Adding elements in a vector in R programming – append() method. append() method in R programming is used to append the different types of integer values into a vector in the last. Return: Returns the new vector after appending given value.

How do you add an element to a vector array?

Insertion: Insertion in array of vectors is done using push_back() function. Above pseudo-code inserts element 35 at every index of vector <int> A[n]. Traversal: Traversal in an array of vectors is perform using iterators. Above pseudo-code traverses vector <int> A[n] at each index using starting iterators A[i].


1 Answers

This should do what you want.

vector<int>myVec(3);
myVec.insert(myVec.begin() + INTEGER_OFFSET, DATA);

Please be aware that iterators may get invalidated when vector get reallocated. Please see this site.

EDIT: I'm not sure why the other answer disappeared...but another person mentioned something along the lines of:

myVec.insert(INDEX, DATA);

If I remember correctly, this should be just fine.

like image 154
nevets1219 Avatar answered Oct 22 '22 02:10

nevets1219