Vector is a common container in the C + + Standard Template Library, like arrays, vectors use contiguous storage space to hold elements, using pointer offsets to quickly access elements (often considered O1 complexity), unlike arrays where the size is variable, Using dynamically allocated memory to hold elements inside the vector means that the vector will need to reallocate memory when it grows and copy the original data to that memory unit, which requires significant overhead, so that the vector does not reallocate memory space every time a new element is added. The actual vector capacity (capacity) is usually much largerthan the actual size (size). Reference data structure (c + + language version), we can see that the growth of capacity has multiplied:
void vector<t>:: Expand () { ifreturn; New 1 ]; for (int0; i < _size; i++) = Oldelem[i]; Delete [] oldelem;}
Common construction methods for vectors:
- The default construct constructs an empty container with no elements.
- Constructs n elements, each element is M
- Interval constructs, which can be iterators or array intervals
- Copy Construction
The following is a specific code example:
std::vector<int>First ; Std::vector<int> Second (5, -); Std::vector<int>third (Second.begin (), Second.end ()); Std::vector<int> fourth (third);//Copy Construction intAry[] = {6, A, -,2}; Std::vector<int> Fifth (ary, ary +sizeof(ary)/sizeof(int) ); for(Auto it = Fifth.begin (); It! = Fifth.end (); + +it) std::cout<<' '<< *it; Std::cout<<Std::endl;
Vector of the C + + Standard Template Library (Boolan)