c++ insert into vector at known position

2019-03-14 16:20发布

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.

3条回答
甜甜的少女心
2楼-- · 2019-03-14 16:35

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

frame 10

print vnum

to check. In fact, if you haven't just abbreviated in your question, I've just found your bug. Your 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 line gives the insertion point relative to the start of some other variable called vertices, not the one you want to insert into.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-14 16:45

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.

查看更多
beautiful°
4楼-- · 2019-03-14 16:59

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 should do it. There is a now deleted answer that you can construct an iterator from an index, but I've never see that before. If that's true, that's definitely the way to go; I'm looking for it now.

查看更多
登录 后发表回答