The data structure provided by the class template vector has random access to consecutive memory locations. In this way, you can use the subscript operator [] to efficiently and directly access any element in the vector. Just like the original array in C and C ++. When the data in the container must be conveniently accessed by subscript or sorted as needed. The longest use is the class template vector. When the memory of the vector is exhausted, a larger memory will be allocated, the original data will be copied to the new memory and the old memory will be destroyed.
Tip: selecting a vector container can achieve optimal random access performance.
# Include <iostream>
Using namespace STD;
# Include <vector>
Using STD: vector; // to use a class template vector, this header file must be included.
Template <typename T> void printvector (const vector <t> & integers2 );
Int main ()
{
Const int size = 6;
Int arry [size] = {1, 2, 3, 4, 5, 6 };
Vector <int> intergers;
Cout <"The initial size of intergers is:" <intergers. Size ()
<"\ Nthe inttial capacity of intial is:" <intergers. Capacity ();
Intergers. push_back (2 );
Intergers. push_back (3 );
Intergers. push_back (4 );
Cout <"\ nthe size of intergers is" <intergers. Size ()
<"\ Nthe capacity of intergers is" <intergers. Capacity ();
// The usage of the vector size and capacity functions is demonstrated above.
// Capacity returns the number of elements that can be saved before the vector dynamically changes the size to accommodate more elements.
Cout <"\ noutput intergers :";
For (int * PTR = arry; PTR! = Arry + size; PTR ++) // arry + size points to 6
{
Cout <* PTR <'';
}
Cout <Endl;
For (INT I = 0; I <= size; I ++) // The result shows that C ++ makes the last element equal to the next element.
{
Cout <"<* (arry + I );
}
Cout <Endl;
Cout <"\ noutput vector using interator notion :";
Printvector (intergers );
Cout <"\ nreversed contents of vector intergers :";
Vector <int>: reverse_iterator re; // A reverse_iterator is declared here, which can be used for reverse iteration of vector.
// Like begin and end. The rbegin and rend functions return a const_reverse_iterator or reverse_iterator based on whether the container is a constant.
Vector <int>: reverse_iterator temiterator = intergers. rend ();
For (RE = intergers. rbegin (); Re! = Temiterator; ++ re)
{
Cout <* Re <'';
}
Cout <Endl;
Return 0;
}
Template <typename T>
Void printvector (const vector <t> & integers2)
{
Typename vector <t>: const_iterator ci;
For (CI = integers2.begin ();
CI! = Integers2.end (); CI ++)
Cout <* CI <'';
}