问题
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.
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...
回答1:
myVector[x] = o;
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.
If you want to make sure that it checks for out-of-bound-access also, then use at() as:
myVector.at(x) = o;
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.
- Why is using "vector.at(x)" better than "vector[x]" in C++?
回答2:
myVector[x] = o
does something completely different from using myVector.push_back(o)
(or using insert
). Therefore which method is correct depends on what you are trying to do:
myVector[x] = o
doesn't insert in the vector, but replaces the element at positionx
witho
. Therefore the length of thevector
doesn't change and the value which was previously at positionx
isn't in thevector
any more. If the length ofmyVector
wasn't bigger thenx
this will result in an out of bounds access, leading to undefined behaviourmyVector.push_back(o)
will inserto
at the end ofmyVector
. Therefore after this operation the length of thevector
will be increased by one and the last element ofmyVector
will beo
. No values have been removed frommyVector
.myVector.insert(i, o)
will inserto
at an arbitrary position, specified by the iteratori
. Therefore the length of the vector will be increased by one and the"ith"
element (element numbermyVector.begin() - i
) will beo
回答3:
It will work in case you are not trying to access it out of its bounds, i.e. vector size is greater than x.
回答4:
It's only valid if vector's size is at least x+1. If it's not, you're accessing it out of bounds.
If you declare the vector like this:
std::vector<Object_I_madeup> myVector(10); // construct the vector with size 10
// and default-initialize its elements
then you can safely access indexes 0 - 9. Your vector in the example is empty, though, there isn't yet a valid index to it.
回答5:
If you're looking for a java-like equivalent of the ArrayList.set()
method, you can do it more closely via
void setAt(int x, Object_I_madeup o)
{
myVector.at(x) = o;
}
Much like the Java version, vector::at()
will throw an exception if the vector is not large enough. Note, this makes a copy of the object (actually, two, since you're also passing by value to the function).
来源:https://stackoverflow.com/questions/12204206/inserting-into-a-stdvector-at-an-index-via-the-assignment-operator