c++ vector container

1. Introduction

Vector is a Sequence Container that encapsulates a dynamically sized array. Like any other type of container, it can store various types of objects. You can simply think of a vector as a dynamic array that can store any type.

1.1 The difference between vector and ordinary array

Ordinary arrays are static, the space size is determined during initialization, and dynamic expansion is not supported;
vector can be regarded as a dynamic array, which can store any data (both basic data types and custom data types can be used), and supports dynamic expansion space.

2.Constructor of vector container

Vector container can be regarded as a single-ended array. The constructors include: no-parameter construction, parameterized construction, and copy construction.

vector container:->single-ended array

  • The difference between vector and ordinary array:
    Ordinary arrays are static spaces and are allocated upon creation.
    vector supports dynamic expansion
  • Commonly used iterators for vector containers: < /strong>
    v.rend() –>Points to the previous position of the first element
    v.end() –>Points to the next position of the last element
    v.begin() –>points to the first element
  • The iterator of the vector container supports random access Iterator
  • vector constructor:
    Construction without parameters:vector< T > v;
    Construction with parameters:vector(v.begin(),b.end()); –Copy the content between begin and end
    ?vector(n,elem); //Copy the contents of n elem
    Copy construction: vector(const vector & amp;v);
  • Example of using vector constructor:
#include <iostream>
using namespace std;
#include <vector>
void PrintVector(const vector< int > & amp; ptr)
{<!-- -->
//If the vector passed in is a constant, an iterator is required and you need to use: const_iterator
for ( vector< int >:: const_iterator v = ptr.begin(); v != ptr.end(); v + + )
{<!-- -->
cout << *v << " ";
}
cout << endl;
}
void test()
{<!-- -->
vector< int > vtr; //Default construction
for (int i = 0; i < 5; i + + )
{<!-- -->
vtr.push_back(i);
}
PrintVector(vtr);
vector< int > v2(vtr.begin(), vtr.end());//Copy the content between begin~end
PrintVector(v2);
vector< int > v3(10, 5);//Assign 10 5’s
PrintVector(v3);
vector< int >v4(v3);//copy construction
PrintVector(v4);
}
int main()
{<!-- -->
test();
system("pause");
}

3.vector assignment

vector assignment can be done directly using “=” assignment, or using member function assign.

vector assignment:
vector & amp;operator=(const vector & amp;v);//overload=
assign(beg,end);//Assign the beg~end interval
assign(n,elem);//N elem assignments


  • Example of assignment operation:
#include <iostream>
using namespace std;
#include <vector>

void PrintVector(const vector< int > & amp; p)
{<!-- -->
for (vector< int >::const_iterator ptr = p.begin(); ptr != p.end(); ptr + + )
{<!-- -->
cout << *ptr<< " ";
}
cout << endl;
}
void test()
{<!-- -->
vector< int > v;
for (int i = 0; i < 5; i + + )
{<!-- -->
v.push_back(i);
}
PrintVector(v);
vector< int > v2 = v;//equal sign assignment
PrintVector(v2);
vector< int > v3(v.begin(), v.end());//Interval assignment
PrintVector(v3);
vector< int > v4(5, 666);//5 666 assignments
PrintVector(v4);
}
int main()
{<!-- -->
test();
system("pause");
}

4.vector gets the capacity and number of members

Vector is the same as an ordinary array, and the subscripts start from 0. To obtain the capacity, use the capacity() function. To determine whether the container is empty, use the empty() function. To obtain the number of members, use the size() function. You can also use the resize function to specify the container size;

The capacity and number of members of the vector container:
Determine whether the vector container is empty: empty()
Capacity:capacity()
Number of elements in the container: size()
Specify the container length as num:resize(int num);
If the container becomes longer, it will be filled with the default value, which is 0
If the container becomes smaller, elements beyond the end will be deleted
The length pointed to the container is num:resize(int num,elem);
If the container becomes longer, fill it with elem
If the container becomes smaller, elements beyond the end will be deleted
  • Usage example:
#include <iostream>
using namespace std;
#include <vector>
void PrintVector(const vector< int > & amp; p)
{<!-- -->
for (vector< int >::const_iterator ptr = p.begin(); ptr != p.end(); ptr + + )
{<!-- -->
cout << *ptr << " ";
}
cout << endl;
cout << "Capacity:" << p.capacity();
cout << endl;
cout << "Number of elements:" << p.size();
cout << endl;
}
void test()
{<!-- -->
vector< int > vtr;
for (int i = 0; i < 5; i + + )
{<!-- -->
vtr.push_back(i);
}
PrintVector(vtr);
//Specify container length
vtr.resize(10,666);//The specified length is 10, and if it exceeds, it will be filled with 666
PrintVector(vtr);
vtr.resize(3);//If the specified length is less than the actual length, the excess elements will be deleted, but the excess space will still exist.
PrintVector(vtr);
vector< int >v2;
v2.resize(5);//If the filling value is not specified, the default is 0
if (v2.empty())
{<!-- -->
cout << "v2 is empty" << endl;
}
PrintVector(v2);
}
int main()
{<!-- -->
test();
system("pause");
}


Note: During the resize() function, if the specified size is larger than the original space, the container will be expanded; if the specified size is smaller than the original space, the excess members will be deleted, but the space size will not be deleted;

5.Deletion and insertion of vector container members

The vector container is a single-ended array, and data can be inserted from the end through the bush_back() function.
pop_back() deletes data from the end;
To insert data from a specified location, you can use the insert() member function, which has multiple overloaded versions.
To delete data from a specified location, you can use the erase() member function, which has multiple overloaded versions;
The clear() function implements clearing the container.
Vector insertion and deletion:
push_back();//Tail insertion
pop_back(); //Tail deletion
insert(const_iterator pos,elem);//The iterator points to position pos to insert element elem
insert(const_iterator pos,int count,elem)//The iterator points to position pos and inserts count elements elem
erase(const_iterator pos);//Delete the element pointed to by the iterator
erase(const_iterator start,const_iterator end);//Delete elements between iterator start~end
clear();//Delete all elements in the container

  • Implementation example:
#include <iostream>
using namespace std;
#include <vector>
class Person
{<!-- -->
friend ostream & amp; operator<<(ostream & amp; cout, const Person & amp; per);
public:
Person() {<!-- -->
}
Person(int age, string name) :age(age), name(name)
{<!-- -->
}
Person & operator=(Person p)
{<!-- -->
this->age = p.age;
this->name = p.name;
return *this;
}
private:
int age;
string name;
};
ostream & amp; operator< <(ostream & amp; cout, const Person & amp;per)
{<!-- -->
cout << "Name:" << per.name << "tAge:" << per.age;
return cout;
}
void PrintVector(const vector<Person> & amp; p)
{<!-- -->
for (vector< Person >::const_iterator ptr = p.begin(); ptr != p.end(); ptr + + )
{<!-- -->
cout << *ptr << endl;
}
}
void test()
{<!-- -->
//instantiate object
Person v1(18,"小王");
Person v2(18, "Xiao Li");
Person v3(18, "Xiao Liu");
Person v4(18, "Xiao Chen");
Person v5(18, "小江");
Person v[5] = {<!-- --> v1,v2,v3,v4,v5};
for (int i = 0; i < sizeof(v) / sizeof(v[0]); i + + )
{<!-- -->
cout < < v[i] < < endl;
}
cout << "--------------------vector-------------------" << endl;
//Create container
vector<Person>vtr;
//Tail insert
for (int i = 0; i < 5; i + + )
{<!-- -->
vtr.push_back(v[i]);//Assignment
}
PrintVector(vtr);
//Delete tail
cout << "t tail deleted" << endl;
vtr.pop_back();
PrintVector(vtr);
//Insert
cout << "tinsert" << endl;
Person temp(24, "Lao Lu");
vtr.insert(vtr.begin(), temp);
PrintVector(vtr);
cout << "Insert 3 values in the third position of t" << endl;
vector<Person>::iterator ptr = vtr.begin();
ptr + = 3;
vtr.insert(ptr, 3,temp);
PrintVector(vtr);
cout << "tDelete the value at the first position" << endl;
vtr.erase(vtr.begin());
PrintVector(vtr);

cout << "tDelete the values from the 3rd to 6th position" << endl;
ptr = vtr.begin();
vtr.erase(ptr + 3, ptr + 6);
PrintVector(vtr);

cout << "tclear" << endl;
vtr.clear();//or use vtr.erase(vtr.begin(),vtr.end);
PrintVector(vtr);
cout << "Space size:" << vtr.capacity();
cout << endl;
cout << "Number of elements:" << vtr.size();
cout << endl;
}
int main()
{<!-- -->
test();
system("pause");
}

6.vector container data access

Vector containers can also access members with [] just like ordinary arrays. In addition, you can also use the at() member function to read and write data;

vector data access
at(int idx);//Return the content corresponding to the subscript
operator[];//overloaded[]
front();//Return the first element in the container
back();//Return the last element in the container

  • Implementation example:
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>

void PrintVector(int val)
{<!-- -->
cout << val << " ";
}
void test()
{<!-- -->
\t
vector<int> vtr;
for (int i = 0; i < 5; i + + )
{<!-- -->
vtr.push_back(i);
}
for_each(vtr.begin(), vtr.end(), PrintVector);
cout << endl;
cout << "First value:" << vtr.front() << endl;
cout << "Last value:" << vtr.back() << endl;
vtr[0] = 100;
cout << "vtr[0]=" << vtr.at(0) < < endl;
\t
}

int main()
{<!-- -->
test();
system("pause");
}


7.vector container interchange elements

In a vector container, members of two containers can be exchanged through the member function swap() function.
Note: swap exchanges elements and also exchanges space sizes.

vector container interchange
swap(vec);//Exchange the elements in vec with its own elements
Note: swap exchanges elements and also exchanges space sizes.

  • Usage example:
#include <iostream>
#include <vector>
using namespace std;
void PrintVector(const vector<int> & amp; p)
{<!-- -->
for (vector<int>::const_iterator ptr = p.begin(); ptr != p.end(); ptr + + )
{<!-- -->
cout << *ptr << " ";
}
cout << endl;
}
void test()
{<!-- -->
vector<int> vtr(10,666);
vector<int> vtr2;
for (int i = 0; i < 5; i + + )
{<!-- -->
vtr2.push_back(i);
}
cout << "\tBefore swap" << endl;
PrintVector(vtr);
PrintVector(vtr2);
cout << "Vtr size:" << vtr.capacity() << "\tNumber of elements:"<<vtr.size()<<endl;
cout << "Vtr2 size:" << vtr2.capacity() << "\tNumber of elements:" << vtr2.size()<<endl;
cout << "\tAfter swap" << endl;
vtr2.swap(vtr);
PrintVector(vtr);
PrintVector(vtr2);
cout << "Vtr size:" << vtr.capacity() << "\tNumber of elements:" << vtr.size() << endl;
cout << "Vtr2 size:" << vtr2.capacity() << "\tNumber of elements:" << vtr2.size() << endl;
}
//Exchange elements and spaces through swap
void test02()
{<!-- -->
vector<int>vtr;
//Initialization
for (int i = 0; i < 100000; i + + )
{<!-- -->
vtr.push_back(i);
}
cout << "Vtr size:" << vtr.capacity() << "\tNumber of elements:" << vtr.size() << endl;
vtr.resize(5);//Respecify the length to 5
cout << "Vtr size:" << vtr.capacity() << "\tNumber of elements:" << vtr.size() << endl;
vector<int>(vtr).swap(vtr);
/*
vector<int>(vtr) --Use an anonymous object and initialize the anonymous object to vtr

vector<int>(vtr).swap(vtr); --When exchanging anonymous objects through the swap function, the memory can be shrunk at this time
*/
cout << "Vtr size:" << vtr.capacity() << "\tNumber of elements:" << vtr.size() << endl;
}
int main()
{<!-- -->
test();
cout << "------------------test02 example--------------------------------" < <endl;
test02();
system("pause");
}


Because the swap function can not only interchange elements, but also the size of the space can be interchanged, so you can use the swap() function to rationally use the space during some clearing situations and avoid wasting space resources.

8.vector container reserved space

The

reserve() member function can specify the space size to reserve space for the vector container.
The difference between the reserve function and the resize() function:
The resize() function will directly initialize the space after specifying the size;
The size specified by the reserve() function will not initialize the space. The reserved space cannot be accessed directly and must be accessed after assignment.
reserve(int len);//The container reserves elements of len length, the reserved position is initialized, and the elements are inaccessible
  • Usage example:
#include <iostream>
using namespace std;
#include <vector>
void test()
{<!-- -->
vector<int>vtr;
vtr.reserve(10);
cout << "Space size:" << vtr.capacity() << "Number of elements:"<<vtr.size()<<endl;
vector<int> vtr2;
vtr2.resize(10);//Specify the length
cout << "Space size:" << vtr2.capacity() << "Number of elements:" << vtr2.size() << endl;
}

void test02()
{<!-- -->
vector<int> vtr;
int* p=NULL;
cout << "Not applicable reserved space:" << endl;
int num = 0;
for (int i = 0; i < 100000; i + + )
{<!-- -->
vtr.push_back(i);
if (p != & amp;vtr[0])
{<!-- -->
p = &vtr[0];
num + + ;
}
}
cout << "Dynamic expansion space times:" << num<<endl;

vector<int> vtr2;
vtr2.reserve(100000);//Reserve 100000 space
p = NULL;
cout << "Use reserved space:" << endl;
num = 0;
for (int i = 0; i < 100000; i + + )
{<!-- -->
vtr2.push_back(i);
if (p != & amp;vtr2[0])
{<!-- -->
p = &vtr2[0];
num + + ;
}
}
cout << "Dynamic expansion space times:" << num << endl;

}
int main()
{<!-- -->
test();
cout << "\tExample 2:" << endl;
test02();
system("pause");
}


The vector container space is dynamically expanded based on the members. If you know approximately how much space will be used from the beginning, you can use the reserve() function to specify it, which can reduce the number of intermediate dynamic expansions.

syntaxbug.com © 2021 All Rights Reserved.