Standard Template Library (STL) learn to explore the vector container

Source: Internet
Author: User

Standard Template Library (STL) learn to explore the vector container
C + + Vectors
Vector is part of the C + + Standard Template Library, which is a multifunctional template class and function library that can manipulate a variety of data structures and algorithms. Vector is considered to be a container because it can store various types of objects like a container, in short, a vector is a dynamic array that can hold any type and can add and compress data. In order to be able to use vectors, you must include the following code in your header file: #include <vector>
constructor function.
The Vectors contains a series of continuously stored elements that behave in a similar array. Accessing any element in the vector, or adding elements from the end, can be done in constant-level time complexity, while the element looking for a particular value or inserting an element into the vector is a linear time complexity.
The list of functions is as follows:
Constructors constructor function
Operators to assign or compare vectors
Assign () assigns a value to an element in a vector
At () returns the element at the specified position
Back () returns the last element
Begin () returns an iterator to the first element
Capacity () returns the number of elements the vector can hold (without reallocating memory)
Clear () Clears all elements
Empty () to determine if the vector is empty (null when returning True)
End () returns an iterator to the last element (the next position of the last element is actually pointed)
Erase () deletes the specified element
Front () returns the first element
Get_allocator () returns the vector's memory allocator
Insert () inserts the element into the vector
Max_size () returns the maximum number of elements the vector can hold (upper limit)
Pop_back () removes the last element
Push_back () Adds an element at the end of the vector
Rbegin () returns an inverse iterator to the tail of a vector
Rend () returns the inverse iterator to the start of the vector
Reserve () Sets the minimum number of elements for the vector to accommodate
Resize () Change the size of the vector element number
Size () returns the number of vector elements
Swap () swap two vectors

/////////////////////////////////////////////////////////////////////////////////////
Function Detail Description
constructor function
Grammar:
Vector ();
Vector (size_type num, const type &AMP;VAL);
Vector (const vector &from);
Vector (input_iterator start, Input_iterator end);
C + + vectors can be constructed using any of the following parameters:
No parameters-constructs an empty vector,
Quantity (num) and Value (val)-constructs a vector that initially puts the elements of NUM values to Val
Vector (from)-constructs a vector that is the same as the vector from
Iterator (start) and iterator (end)-Constructs a vector (note: half-open interval) of an interval element with an initial value of [Start,end].
For example, the following example constructs a vector containing 5 elements with a value of 42
Vector<int> v1 (5, 42);
Operator
Grammar:
V1 = = V2
V1! = V2
V1 <= v2
V1 >= v2
V1 < v2
V1 > V2
V[]
C + + vectors can use standard operators: = =,! =, <=, >=, <, and;. You can use the [] operator to access elements in a particular location in the vector.
Two vectors are considered to be equal if:
They have the same capacity
All elements of the same position are equal.
The comparison between the sizes of vectors is in accordance with the dictionary rules.
Assign function
Grammar:
void assign (Input_iterator start, Input_iterator end);
void assign (Size_type num, const type &AMP;VAL);
The Assign () function either assigns an element of the interval [start, end] to the current vector, or assigns a number of elements in the Val value to the vector. This function clears the previous contents of the vector assignment.
at function
Grammar:
TYPE at (Size_type Loc);
The at () function returns a reference to the element of Loc at the current vector specified position. The at () function is more secure than the [] operator because it does not allow you to access elements that are out of bounds within the vector. For example, consider the following code:
Vector<int> V (5, 1);
for (int i = 0; i < i++) {
cout << "Element" << I << "is" << V[i] << Endl;
}
This code accesses the elements after the end of the vector, which can lead to very dangerous results. The following code will be more secure:
Vector<int> V (5, 1);
for (int i = 0; i < i++) {
cout << "Element" << I << "is" << v.at (i) << Endl;
}
Instead of trying to access illegal values in memory, the at () function can tell if the access is out of bounds and throw an exception out_of_range when it crosses the boundary.
Back function
Grammar:
TYPE back ();
The back () function returns a reference to the last element of the current vector. For example:
Vector<int> v;
for (int i = 0; i < 5; i++) {
V.push_back (i);
}
cout << "The first element is" << V.front ()
<< "and the last element are" << v.back () << Endl;
This code produces the following results:
The first element is 0 and the last element is 4
Begin function
Grammar:
Iterator begin ();
The Begin () function returns an iterator that points to the starting element of the current vector. For example, the following paragraph uses an iterator to display all the elements in the vector:
Vector<int> v1 (5, 789);
Vector<int>::iterator it;
for (it = V1.begin (); It! = V1.end (); it++)
cout << *it << Endl;
Capacity function
Grammar:
Size_type capacity ();
The capacity () function returns the number of elements that the current vector can hold before the memory allocation is re-allocated.
Clear function
Grammar:
void Clear ();
The clear () function deletes all elements in the current vector.
Empty function
Grammar:
bool Empty ();
If the current vector does not contain any elements, the empty () function returns True, otherwise false is returned. For example, the following code empties a vector and displays all the elements in reverse order:
Vector<int> v;
for (int i = 0; i < 5; i++) {
V.push_back (i);
}

while (!v.empty ()) {
cout << v.back () << Endl;
V.pop_back ();
}
End Function
Grammar:
Iterator End ();
The end () function returns an iterator that points to the next position of the element at the end of the current vector. Note that if you want to access the end element, you need to subtract 1 from the iterator first.
erase function
Grammar:
Iterator Erase (iterator Loc);
Iterator Erase (iterator start, iterator end);
The Erase function either deletes the element of LOC at the specified location or removes all elements of the interval [start, end]. The return value is an iterator to the next position of the last element that was deleted. For example:
Create a vector that is placed in the first 10 characters of the alphabet
Vector<char> Alphavector;
for (int i=0; i <; i++)
Alphavector.push_back (i + 65);
int size = Alphavector.size ();
Vector<char>::iterator Startiterator;
Vector<char>::iterator Tempiterator;
for (int i=0; i < size; i++)
{
Tartiterator = Alphavector.begin ();
Alphavector.erase (Startiterator);
Display the vector
for (Tempiterator = Alphavector.begin (); Tempiterator! = Alphavector.end (); tempiterator++)
cout << *tempiterator;
cout << Endl;
}
This code will show the following output:
Bcdefghij
Cdefghij
Defghij
Efghij
Fghij
Ghij
HIJ
Ij
J
Front function
Grammar:
TYPE Front ();
The front () function returns a reference to the starting element of the current vector
Get_allocator function
Grammar:
Allocator_type Get_allocator ();
The Get_allocator () function returns the memory allocator of the current vector. In STL, new or alloc is not normally called to allocate memory, and is allocated by means of a allocator object.
Example: Vector<int>v3 (3, 1, V2.get_allocator ());//The V2 memory allocator is involved in constructing V3 as a parameter. In this way, they are two with a memory allocator.
Insert function
Grammar:
Iterator Insert (iterator loc, const TYPE &val);
void Insert (Iterator loc, size_type num, const type &AMP;VAL);
void Insert (Iterator loc, input_iterator start, Input_iterator end);
There are three ways to use the Insert () function:
Inserts an element with a value of Val before Loc at the specified position, returning an iterator to that element.
Inserts a num value Val element before Loc at the specified location
Inserts all elements of the interval [start, end] before Loc at the specified position.
Example:
Create a vector that is placed in the first 10 characters of the alphabet
Vector<char> Alphavector;
for (int i=0; i <; i++)
Alphavector.push_back (i + 65);
Insert four C into vector
Vector<char>::iterator theiterator = Alphavector.begin ();
Alphavector.insert (Theiterator, 4, ' C ');
Displaying the contents of a vector
for (Theiterator = Alphavector.begin (); Theiterator! = Alphavector.end (); theiterator++)
cout << *theiterator;
This code will show:
Ccccabcdefghij
max_size function
Grammar:
Size_type max_size ();
The Max_size () function returns the maximum number of elements that the current vector can hold (including the ability to reallocate memory).
Pop_back
Grammar:
void Pop_back ();
The Pop_back () function deletes an element at the bottom of the current vector, for example:
Vector<char> Alphavector;
for (int i=0; i <; i++)
Alphavector.push_back (i + 65);
int size = Alphavector.size ();
Vector<char>::iterator Theiterator;
for (int i=0; i < size; i++) {
Alphavector.pop_back ();
for (Theiterator = Alphavector.begin (); Theiterator! = Alphavector.end (); theiterator++)
cout << *theiterator;
cout << Endl;
}
This code will display the following output:
Abcdefghi
Abcdefgh
ABCDEFG
ABCDEF
ABCDE
Abcd
Abc
Ab
A
push_back function
Grammar:
void push_back (const TYPE &val);
Push_back () Adds an element with a Val value to the end of the current vector
Rbegin function
Grammar:
Reverse_iterator Rbegin ();
The Rbegin function returns an inverse iterator that points to the end of the current vector. (The actual point to the end of the next position, and its content is the value of the end element, see the inverse of the relevant content)
Example:
vector<int>v1;
for (int i=1;i<=5;i++)
{
V1.push_back (i);
}
Vector<int>::reverse_iterator POS;
Pos=v1.rbegin ();
cout<<*pos<< "";
pos++;
cout<<*pos<<endl;
Output Result: 5 4
rend function
Grammar:
Reverse_iterator rend ();
The rend () function returns an inverse iterator that points to the starting position of the current vector.
Example:
vector<int>v1;
for (int i=1;i<=5;i++)
{
V1.push_back (i);
}
Vector<int>::reverse_iterator POS;
Pos=v1.rend ();
pos--;
cout<<*pos<< "";
pos--;
cout<<*pos<<endl;
Output Result: 1 2
Reserve function
Grammar:
void Reserve (size_type size);
The reserve () function reserves space for the current vector to hold at least a total of size elements. (The actual space may be greater than size)
Resize function
Grammar:
void Resize (size_type size, type val);
The resize () function alters the size of the current vector and assigns a value to the newly created element Val
The difference between resize and reserve
Reserve is a container reservation space, but does not really create an element object, before creating the object, cannot reference the elements inside the container, so when adding new elements, you need to use the push_back ()/insert () function.
Resize is changing the size of the container and creating the object, so after calling this function, you can refer to the object within the container, so when adding a new element, use the operator[] operator, or use an iterator to refer to the element object. Moreover, the form of the two functions is different, the reserve function after a parameter, that is, the space to be reserved container; The resize function can have two parameters, the first parameter is the new size of the container, the second parameter is the new element to be added to the container, and if this argument is omitted, Then the default constructor for the element object is called.
The first contact of these two interfaces may be confused, in fact, the name of the interface is a good description of the function, resize is the reallocation of size, reserve is reserved for a certain space. The two interfaces are different and have common ground. The following is an analysis of their details.
To implement the semantics of resize, the resize interface makes two guarantees:
One is to ensure that the data in the range [0, new_size) is valid, if the subscript index within this interval, Vector[indext] is legal.
The second is to ensure that the range [0, new_size) outside the scope of the data is invalid, if subscript index outside the interval, Vector[indext] is illegal.
Reserve just guarantees that the vector's space size (capacity) reaches at least the size n specified by its argument. Within the range [0, N), if the subscript is index,vector[index] Such access may be lawful and may be illegal, depending on the circumstances.
The common denominator of the resize and reserve interfaces is that they ensure that the space size of the vector (capacity) is at least the size specified by its parameters.
Because the source code of the two interfaces is fairly streamlined, they can be pasted here:
void Resize (Size_type new_size) {Resize (new_size, T ());}
void Resize (size_type new_size, const t& x) {
if (New_size < oldsize)
Erase (Oldbegin + new_size, oldend); Erase data outside the range to ensure that data outside the interval is not valid
Else
Insert (Oldend, new_size-oldsize, x); Fill gaps within the range to ensure that data within the interval is valid
Example:
#include <iostream>
#include <vector>
using namespace Std;
void Main ()
{
vector<int>v1;
for (int i=1;i<=3;i++)
{
V1.push_back (i);
}
V1.resize (5,8);//The two extra spaces are initialized to 8,
For (I=0;i<v1.size (); i++)//resize and reserver do not delete the original element to free up space
{
cout<<v1[i]<< "";
}
cout<<endl;
V1.reserve (7);//The new element has not yet been constructed,
for (i=0;i<7;i++)
{
cout<<v1[i]<< "";//when i>4, cannot access element at this time []
}
cout<<endl;
Cout<<v1.size () <<endl;
Cout<<v1.capacity () <<endl;
}
The output is:
1 2 3) 8 8
1 2 3 8 8-842150451-842150451
5
7
Size function
Grammar:
Size_type size ();
The size () function returns the number of elements that the current vector holds
Swap function
Grammar:
void swap (vector &from);
Swap () function swaps the elements of the current vector and vector from
Example:
vector<int>v1,v2;
for (int i=1;i<=3;i++)
{
V1.push_back (i);
V2.push_back (i);
}
V2.push_back (4);
V2.push_back (5);
V1.swap (v2);
for (int j=0;j<v1.size (); j + +)
{
cout<<v1[j]<< "";
}
cout<<endl;
for (int k=0;k<v2.size (); k++)
{
cout<<v2[k]<< "";
}
cout<<endl;
The output is:
1 2 3) 4 5
1 2 3

Standard Template Library (STL) learn to explore the vector container

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.