Summary of vector clearing methods

Summary of vector clearing methods

Clear vector has two meanings

Meaning 1: Only clear content, not reclaim space

Meaning 2: Clear content and reclaim space

Take a look at this code:

#include <iostream>
#include <vector>
using namespace std;

struct Edge {
    
    
	int v, d;
};

int main() {
    
    
	cout << "****************一维vector***************" << endl;
	Edge e = Edge({
    
     1, 2 });
	vector<Edge> Ve1;
	for (int i = 0; i < 5; ++i)
		Ve1.push_back(e);
	cout << Ve1.size() << ' ' << Ve1.capacity() << endl;
	Ve1.clear();
	cout << Ve1.size() << ' ' << Ve1.capacity() << endl;
	vector<Edge>().swap(Ve1);
	cout << Ve1.size() << ' ' << Ve1.capacity() << endl;

	cout << "****************二维vector***************" << endl;
	vector<vector<Edge> > Ve2(10);
	for (int i = 0; i < 10; ++i) {
    
    
		for (int j = 0; j < 10; ++j)
			Ve2[i].push_back(e);
	}
	cout << Ve2.size() << ' ' << Ve2.capacity() << endl;
	for (int i = 0; i < 10; ++i)
		Ve2.clear();
	cout << Ve2.size() << ' ' << Ve2.capacity() << endl;
	vector<vector<Edge> >().swap(Ve2);
	cout << Ve2.size() << ' ' << Ve2.capacity() << endl;
	return 0;
}

Look at this output again:

Insert picture description here

get conclusion:

If the processed object is a vector, you only need to use the clear() function to clear the content. If it is a multi-vector doll, two points should be paid attention to. First, the line size should be declared when declaring, otherwise it will not give you space and it will cause runtime error! Second: Get each vector[i] and then clear to complete the vector content removal.

If you want to reclaim space, the elegant solution is to swap it with an empty vector! But pay attention, unless this vector is no longer used later, it is best not to do it. This kind of recycling method should be placed in a suitable place, because this is a way to release the memory, and the memory needs to be re-allocated to use it again after release, which is also a costly way.

Guess you like

Origin blog.csdn.net/qq_44274276/article/details/108127918