开发者

c++ insert into vector at known position

开发者 https://www.devze.com 2022-12-21 00:09 出处:网络
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 i

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 inser开发者_如何学Ct into the vector like I would insert into an array, using a specific index.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消