简体   繁体   中英

C++ Vector and Insertion

The insert method for STL containers takes two arguments: an iterator indicating where to insert, and a value to insert. Knowing that insert method defines that a newly inserted value will be inserted before the value currently referred to by the iterator.

Why would it not be appropriate to instead define that insert places the new value after the current value?

The newly inserted method will be in the position that the iterator is pointing to, everything else will be "pushed to the next position".

If you put it past the current item, then you're actually inserting at iterator+1

The iterator points to the item to insert the new item before. Semantically, you are providing the location of the new item.

If instead the item were inserted after, how could you insert at the start of the vector as the first item?

Using the current scheme, items can be inserted anywhere. But under your proposed alternative, you cannot insert at the start without a special case.

  1. Because then you wouldn't be able to perform an insertion at the beginning by writing:

     vect.insert(vect.begin(), value); 
  2. Because then you wouldn't be able to easily perform an insertion at the end by writing

     vect.insert(vect.end(), value); 

After performing the above operations the new value is actually at the begin/end (as evaluated after the insert, the iterators before the insert could be invalidated) just as the code says. If you defined insert any other way, you would have to mess around with +1/-1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM