通过赋值运算符在索引处插入std :: vector [英] Inserting into a std::vector at an index via the assignment operator
问题描述
我是C ++的新手,并且很好奇这是否是插入std :: vector的首选方式
I'm new to C++ and am curious if this is the preferred way of inserting into a std::vector
std::vector<Object_I_madeup> myVector;
void setAt(int x, Object_I_madeup o)
{
myVector[x] = o;
} // set the array location at x to be o.
我之所以问,是因为我看到了很多有关使用 push_back
的信息,或者令人困惑的 insert()
的信息.这种类似Java的方式有效吗?我宁愿那样做...
I ask because I see a lot of things about using push_back
,or the highly confusing insert()
. Is this Java-like way valid? I'd much rather do that...
推荐答案
myVector[x] = o;
只有 x<myVector.size()
.否则,它将调用undefined-behavior,因为在这种情况下,它将尝试访问向量边界之外的元素.
It is well-defined only if x < myVector.size()
. Otherwise, it invokes undefined-behavior, because in that case it attempts to access an element out of the bound of the vector.
如果您想确保它也检查出站访问权限,请使用 at()
为:
If you want to make sure that it checks for out-of-bound-access also, then use at()
as:
myVector.at(x) = o;
现在,如果 x> = myVector.size()
,它将抛出 std :: out_of_range
异常.因此,您必须将此代码放入 try-catch
块中!它们之间的区别将在此处进行详细讨论.
Now it will throw std::out_of_range
exception if x >= myVector.size()
. So you have to put this code in try-catch
block! The difference between them is discussed at great detail here.
这篇关于通过赋值运算符在索引处插入std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!