[ACCEPTED]-c++ insert into vector at known position-insert

Accepted answer
Score: 23

This should do what you want.

myVec.insert(myVec.begin() + INTEGER_OFFSET, DATA);

Please be aware 4 that iterators may get invalidated when 3 vector get reallocated. Please see this 2 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 1 just fine.

Score: 9

It's always nice to wrap these things up:

template <typename T>
T& insert_at(T& pContainer, size_t pIndex, const T::value_type& pValue)
    pContainer.insert(pContainer.begin() + pIndex, pValue);

    return pContainer;

That 5 should do it. There is a now deleted answer 4 that you can construct an iterator from 3 an index, but I've never see that before. If 2 that's true, that's definitely the way to 1 go; I'm looking for it now.

Score: 5

Look at that debugging trace. The last thing 17 that's executed is std::copy(__first=0x90c6fa8, __last=0x90c63bc, __result=0x90c6878). Looking 16 back at what caused it, you called insert 15 giving the position to insert at as 0x90c63bc. std::copy 14 copies the range [first, last) to result, which 13 must have room for last - first elements. This 12 call has last < first, which is illegal 11 (!), so I'm guessing that the position you're 10 giving to insert at is wrong. Are you sure 9 vnum hasn't underflowed somewhere along 8 the line? In GDB with that trace showing, you 7 should run

frame 10

print vnum

to check. In 6 fact, if you haven't just abbreviated in 5 your question, I've just found your bug. Your 4 second line is:

new_mesh->Face(face_loc)->vertices.insert(vertices.begin()+vnum+1, new_vertices[j]);

It should have been:

new_mesh->Face(face_loc)->vertices.insert(new_mesg->Face(face_loc)->vertices.begin()+vnum+1, new_vertices[j]);

The first 3 line gives the insertion point relative 2 to the start of some other variable called vertices, not 1 the one you want to insert into.

More Related questions