Ch9.3: Insert and Erase by Index
Overview
fast_io containers provide insert_index and
erase_index operations. These are bounds-checked
alternatives to iterator-based insertion and erasure. If the index is out
of range, they call fast_terminate().
1. insert_index
#include <fast_io_dsal/vector.h>
#include <fast_io.h>
int main() {
::fast_io::vector<::std::size_t> v{10zu, 20zu, 30zu, 40zu};
// Insert 25 at index 2 (between 20 and 30)
v.insert_index(2zu, 25zu);
// v is now {10zu, 20zu, 25zu, 30zu, 40zu}
// Out-of-range index terminates the program
v.insert_index(100zu, 99zu); // fast_terminate()
}
Available on:
| Container | Single element | Multiple copies | Range |
|---|---|---|---|
vector |
insert_index(idx, val) |
— | — |
deque |
insert_index(idx, val) |
insert_index(idx, count, val) |
insert_range_index(idx, rg) |
bitvec |
insert_index(idx, bit) |
— | — |
2. erase_index
#include <fast_io_dsal/vector.h>
#include <fast_io.h>
int main() {
::fast_io::vector<::std::size_t> v{10zu, 20zu, 30zu, 40zu, 50zu};
// Erase element at index 2 (removes 30)
v.erase_index(2zu);
// v is now {10zu, 20zu, 40zu, 50zu}
// Erase range [first, last) — i.e. left_index=1 (inclusive) to right_index=3 (exclusive)
// Removes elements at index 1 and 2
v.erase_index(1zu, 3zu);
// v is now {10zu, 50zu}
}
Available on:
| Container | Single element | Range [first, last) |
|---|---|---|
vector |
erase_index(idx) |
erase_index(first, last) |
deque |
erase_index(idx) |
erase_index(first, last) |
bitvec |
erase_index(idx) |
erase_index(first, last) |
Note: first and last are
indices, not counts. The range [first, last) means
the left index is inclusive and the right index is exclusive. For
example, erase_index(1zu, 3zu) removes the elements at
index 1 and index 2 (not 3 elements starting at index 1).
Preference: Prefer insert_index /
erase_index over iterator-based operations. They are simpler
to use, harder to misuse, and provide bounds checking for free.
Iterator invalidation: Like their iterator-based
counterparts, insert_index and erase_index
invalidate iterators. For vector and bitvec,
any insertion or erasure invalidates all iterators,
pointers, and references. For deque, iterators are always
invalidated, but pointers and references to non-erased elements
survive push_front() and
push_back() — see Ch9.9 for details.
Key takeaways
insert_index(idx, val)inserts at a position with bounds checking.erase_index(idx)removes one element;erase_index(first, last)removes a range.- Available on
vector,deque, andbitvec. - Out-of-range indices call
fast_terminate(). - Prefer
_indexoperations over iterator-based insert/erase for safety. insert_indexanderase_indexinvalidate iterators. Fordeque, pointers and references to non-erased elements survive end insertions.