JiaHeng-DLUT
7/27/2019 - 10:23 AM

Remove

Remove element(s) from a vector

// Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.
// A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function. 

// 0 1 2 3 4 5 6 7 8 9
cout << vec.size() << endl; // 10
cout << vec.capacity() << endl; // 13
vec.clear();
// 
cout << vec.size() << endl; // 0
cout << vec.capacity() << endl; // 13
// Removes from the vector either a single element (position) or a range of elements ([first,last)).
// This effectively reduces the container size by the number of elements removed, which are destroyed.
// Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. 
// This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).

// 0 1 2 3 4 5 6 7 8 9
cout << vec.size() << endl; // 10
cout << vec.capacity() << endl; // 13
vec.erase(vec.begin() + 5);
// 0 1 2 3 4 6 7 8 9
vec.erase(vec.begin(), vec.end());
// 
cout << vec.size() << endl; // 0
cout << vec.capacity() << endl; // 13
// Removes the last element in the vector, effectively reducing the container size by one.

// 0 1 2 3 4 5 6 7 8 9
cout << vec.size() << endl; // 10
cout << vec.capacity() << endl; // 13
vec.pop_back();
// 0 1 2 3 4 5 6 7 8
cout << vec.size() << endl; // 9
cout << vec.capacity() << endl; // 13
// 0 1 2 3 4 5 6 7 8 9
cout << vec.size() << endl; // 10
cout << vec.capacity() << endl; // 13
remove(vec.begin(), vec.end(), 3);
// 0 1 2 4 5 6 7 8 9 9
remove(vec.begin(), vec.end(), 4); 
// 0 1 2 5 6 7 8 9 9 9
remove(vec.begin(), vec.end(), 5); 
// 0 1 2 6 7 8 9 9 9 9
cout << vec.size() << endl; // 10
cout << vec.capacity() << endl; // 13
// vec.erase(remove(vec.begin(),vec.end(),value),vec.end());
// 删除元素,不填充
// A typical alternative that forces a reallocation is to use swap:
// vector<T>().swap(x);   // clear x reallocating

// 0 1 2 3 4 5 6 7 8 9
cout << vec.size() << endl; // 10
cout << vec.capacity() << endl; // 13
vector<int>().swap(vec);
// 
cout << vec.size() << endl; // 0
cout << vec.capacity() << endl; // 0