当前位置:网站首页>STL_ Vector container

STL_ Vector container

2021-01-23 17:52:49 Southeast Asian monsoon

One 、Vector About the container

vector It's a container that manages elements in a dynamic array .

vector Random access to elements ( Direct access to index values is supported , use [] Operator or at() Method ).

vector Adding or removing elements from the tail is very fast , But it takes time to insert or remove elements in the middle or head .

Two 、vector Object's default construction

vector Using template class to achieve ,vector Object's default construction form :vector<T> vecT;

vector<int> vecInt;     // One store int Of vector Containers .

vector<float> vecFloat;    // One store float Of vector Containers .

vector<string> vecString;   // One store string Of vector Containers .

...                  // You can also set pointer type or custom type in angle brackets .

Class CA{};

vector<CA*> vecpCA;      // To hold CA Object's pointer vector Containers .

vector<CA> vecCA;       // To hold CA Object's vector Containers . Because the storage of container elements is carried out by copying values , So at this time CA You must provide CA Copy constructor for , In order to make sure CA Copy between objects is normal .

3、 ... and 、vector Object with parameters

vector(beg,end); // The constructor will [beg, end) The elements in the interval are copied to themselves . Note that the interval is left closed and right open .

vector(n,elem); // The constructor will n individual elem Copy to yourself .

vector(const vector &vec); // copy constructor

void printVector(vector<int>& v) {
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;
}
	vector<int> vl;// Default structure 

	int arr[] = { 10, 20, 30, 40 };
	vector<int> v2(arr, arr + sizeof(arr) / sizeof(int));
	vector<int> v3(v2.begin(), v2.begin()+3);
	vector<int> v4(v3);
	vector<int> v5(4,5);

	printVector(v2);
	printVector(v3);
	printVector(v4);
	printVector(v5);
/*
 result :
10 20 30 40
10 20 30
10 20 30
5 5 5 5
*/

Four 、vector Assignment

vector.assign(beg,end); // take [beg, end) The copy of the data in the interval is assigned to itself . Note that the interval is left closed and right open .

vector.assign(n,elem); // take n individual elem Copy assignment to itself .

vector& operator=(const vector &vec); // Overload the equal sign operator

vector.swap(vec); // take vec Swapping with its own elements .

	int arr[] = { 10, 20, 30, 40 };
	vector<int> v1(arr, arr + sizeof(arr) / sizeof(int));// Default structure 

	// Member method 
	vector<int> v2;
	v2.assign(v1.begin(), v1.end());

	// heavy load =
	vector<int> v3;
	v3 = v2;

	int arr1[] = { 100, 200, 300, 400 };
	vector<int> v4(arr1, arr1 + sizeof(arr) / sizeof(int));// Default structure 

	printVector(v1);
	printVector(v2);
	printVector(v3);
	printVector(v4);

	cout << "------------------" << endl;

	v4.swap(v1);
	printVector(v1);
	printVector(v2);
	printVector(v3);
	printVector(v4);
/*
 result :
10 20 30 40
10 20 30 40
10 20 30 40
100 200 300 400
------------------
100 200 300 400
10 20 30 40
10 20 30 40
10 20 30 40
*/

5、 ... and 、vector Size

vector.size(); // Returns the number of elements in the container

vector.empty(); // Judge whether the container is empty

vector.resize(num); // Reassign the length of the container to num, If the container becomes longer , Then fill in the new location with the default value . If the container gets shorter , Then the element beyond the length of the container at the end is deleted .

vector.resize(num, elem); // Reassign the length of the container to num, If the container becomes longer , with elem Value to fill in the new location . If the container gets shorter , Then the element beyond the length of the container at the end is deleted .

capacity();// Capacity of container

reserve(int len);// Container reservation len Element length , Reserved position is not initialized , The element is not accessible .

	int arr1[] = { 100, 200, 300, 400 };
	vector<int> v4(arr1, arr1 + sizeof(arr1) / sizeof(int));// Default structure 

	cout << "size:" << v4.size() << endl;
	if (v4.empty()) {
		cout << " empty !" << endl;
	}
	else {
		cout << " Not empty !" << endl;
	}

	printVector(v4);
	v4.resize(2);
	printVector(v4);
	v4.resize(6);
	printVector(v4);
	v4.resize(8, 1);
	printVector(v4);

	for (int i = 0; i < 10000; i++) {
		v4.push_back(i);
	}
	cout << "size:" << v4.size() << endl;  
	cout << " Capacity :" << v4.capacity() << endl;// Capacity doesn't have to be equal to size
/*
 result :
size:4
 Not empty !
100 200 300 400
100 200
100 200 0 0 0 0
100 200 0 0 0 0 1 1
size:10008
 Capacity :12138
*/

6、 ... and 、vector Add remove operation at the end

vector.push_back(); // Add an element at the end of the container

vector.pop_back();; // Remove the last element in the container

	int arr1[] = { 100, 200, 300, 400 };
	vector<int> v1(arr1, arr1 + sizeof(arr1) / sizeof(int));// Default structure 

	v1.push_back(500);
	v1.push_back(600);
	v1.push_back(700);
	v1.pop_back();
	printVector(v1);
/*
 result :
100 200 300 400 500 600100 200 300 400 500 600
*/

7、 ... and 、vector Data access for

vector.at(int idx); // Returns the index idx The data , If idx Transboundary , Throw out out_of_range abnormal .

vector[int idx];// Returns the index idx The data , When crossing the border , Run directly to report an error

vector.front();// Returns the first data element in the container

vector.back();// Returns the last data element in the container

	int arr1[] = { 100, 200, 300, 400 };
	vector<int> v4(arr1, arr1 + sizeof(arr1) / sizeof(int));// Default structure 

	// difference : at Throw exceptions  [] Don't throw exceptions 
	for (int i = 0; i < v4.size(); i++) {
		cout << v4[i] << " ";
	}
	cout << endl;

	for (int i = 0; i < v4.size(); i++) {
		cout << v4.at(i) << " ";
	}
	cout << endl;

	cout << "front:" << v4.front() << endl;
	cout << "back:" << v4.back() << endl;
/*
 result :
100 200 300 400
100 200 300 400
front:100
back:400
*/

8、 ... and 、vector Insert and delete

vector.insert(pos,elem); // stay pos Insert a elem Copies of elements , Returns the location of the new data .

vector.insert(pos,n,elem); // stay pos Position insert n individual elem data , No return value .

vector.insert(pos,beg,end); // stay pos Position insert [beg,end) Interval data , No return value

vector.clear(); // Remove all data from the container

vector.erase(beg,end); // Delete [beg,end) Interval data , Return to the next data location .

vector.erase(pos); // Delete pos Location data , Return to the next data location .

	vector<int> v;
	v.push_back(10);
	v.push_back(20);
	// The first interpolation 
	v.insert(v.begin(), 30);
	v.insert(v.end(), 40);

	v.insert(v.begin() + 2, 100); //vector Support random access 

	// Support array subscripts , Random access is generally supported 
	// Iterators can directly +2 +3 -2 -5 operation 
	printVector(v);

	// Delete 
	v.erase(v.begin());
	printVector(v);
	v.erase(v.begin() + 1, v.end());
	printVector(v);
	v.clear();
	cout << "size:" << v.size() << endl;
/*
 result :
30 10 100 20 40
10 100 20 40
10
size:0
*/

Nine 、 Skillfully use swap, Shrink memory space

vector<T>(x).swap(x); // among ,x Refers to the container to be operated on ,T Store the type of the element for the container .

	//vector Additive elements   He will grow automatically   When you delete elements , It doesn't automatically decrease 

	vector<int> v;
	for (int i = 0; i < 100000; i++) {
		v.push_back(i);
	}

	cout << "size:" << v.size() << endl;
	cout << "capacity:" << v.capacity() << endl;

	v.resize(10);
	cout << "--------------" << endl;
	cout << "size:" << v.size() << endl;
	cout << "capacity:" << v.capacity() << endl;

	// Shrink the space 
	vector<int>(v).swap(v);

	cout << "--------------" << endl;
	cout << "size:" << v.size() << endl;
	cout << "capacity:" << v.capacity() << endl;
/*
 result :
size:100000
capacity:138255
--------------
size:10
capacity:138255
--------------
size:10
capacity:10
*/

Ten 、reserve Reserve space

vector Of reserve Added vector Of capacity, But it's size There is no change ! and resize Changed the vector Of capacity It also increases its size!

Here's why :

  • reserve It's container space , But you don't really create element objects in space , So before adding new objects , You can't refer to an element in a container . When you add new elements , To be called push_back()/insert() function .
  • resize It's changing the size of the container , And creating objects , therefore , After calling this function , You can refer to the objects in the container , So when you add new elements , use operator[] The operator , Or use iterators to refer to element objects . Call again at this point push_back() function , It's added to this new space .
	int num = 0;
	int* address = NULL;

	vector<int> v;
	v.reserve(100000);
	for (int i = 0; i < 100000; i++) {
		v.push_back(i);
		if (address != &(v[0])) {
			address = &(v[0]);
			num++;
		}
	}

	cout << "num:" << num << endl;// apply num Subspace 
/*
 result :
num:1
*/

If one vector Use default capacity, So in push_back During operation , According to the number of elements added , Dynamic automatic allocation of space ,2^n Increasing ; If you declare vector When , Use explicitly capacity(size_type n) To specify the vector The capacity of , So in push_back In the process of ( The number of elements does not exceed n),vector There's no automatic allocation of space , Improve program efficiency .

版权声明
本文为[Southeast Asian monsoon]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/01/20210123175200874a.html