Vector is a variable size array
advantage: Find Fast, and at the end of the increase delete quickly
Implementation Principle
Vectors, like array, occupy a contiguous amount of storage space, which means they can be accessed through the offset of the pointer.
vector uses dynamic array to store data, and when the newly inserted data reaches the array's storage length, it is costly to reallocate the memory space while moving the data in the array to the new space, so the vector's real space is larger than the space needed to store the data, Allocate additional space to store data that may be stored.
Defining and initializingDefine an empty vector
Vector<t> v;
Define a vector copy
Vector<t> v1 (v);
Defined and initialized
Vector<t> V (n,i);//define a vector with a length of N and an initial value of I
Define a specific length
Vector<t> v (n);
Basic Operations
Capacity
Size (): Returns the magnitude of a vector
Empty (): Returns whether the vector is empty
Element Access
Front (): Returns the value of the first element of a vector
End (): Returns the value of the last element of a vector
Modifiers
Push_back (val): Add a new element to the vector
Pop_back (): Remove vector last element
Insert (position of vector iterator, value) or insert (position of vector iterator, length, value) or insert (position of vector iterator, position of iterator 1, position of iterator 2)
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> VEC (2);
std::vector<int> Res;
Std::vector<int>::iterator it = Res.begin ();
Res.insert (it, 2);
Res.insert (it + 2, Vec.begin (), Vec.end ());
Res.insert (it, Vec.begin (), Vec.begin () + 2);
return 0;
}
Traversal
There are usually two ways to traverse the iterator by using the subscript
#include <iostream> #include <vector> int main () {std::vector<int> VEC (10
);
for (int i = 0; i < vec.size (); i++) {std::cout << vec[i] << Std::endl; for (Std::vector<int>::iterator it = Vec.begin (); it!= vec.end (); ++it) {std::cout <<*IT<&L T
Std::endl;
return 0; }