std::vector
(And std::copy()
)¶
Basics¶
C array drawbacks
C arrays are fixed-size
Once allocated, they cannot change size
⟶ rather unflexible
std::vector<>
to the rescue
std::vector
: Commonalities with C arraysLies in contiguous memory ⟶ efficient CPU cache usage
Index based access (
a[2]
)Pointer arithmetics via STL iterators
std::vector
: Differences from C arraysCan grow dynamically (
push_back()
,emplace_back()
, …)All sorts of manipulation; e.g. inserting and removing elements at any position
Can also shrink if you tell it to (
shrink_to_fit()
)
Dynamicity Details¶
STL Iterators: Pointer Arithmetic On A std::vector<>
¶
Index based iteration is cumbersome/loud
Remember the beauty?
while (begin != end) *begin++; // <--- beauty!
Difference:
begin
andend
pointers are STL iteratorsC array
std::vector
int a[] = {100, 200, 300}; int *begin = a; int *end = a + 3;
std::vector<int> a = {100, 200, 300}; std::vector<int>::iterator begin = a.begin(); std::vector<int>::iterator end = a.end();
Much typing ⟶ see C++11 auto keyword
Alternative to pointer-loops (but not always applicable): range based for
Algorithms And Containers : std::copy
¶
std::vector<>
is a generalized arrayWhy not use
std::copy()
on it?Copy
std::vector
to C arrayCopy C array to
std::vector
Any mixture possible
A number of pitfalls though
⟶ allocation! For example …
Preallocate destination vector
Use
std::back_insert_iterator