Several ways of deleting elements in C++ STL vector

Posted by super_man on Sun, 06 Feb 2022 07:03:21 +0100

Reproduced in: Several ways of deleting elements in C++ STL vector (super detailed) (biancheng.net)

As mentioned earlier, whether you are accessing, adding or inserting elements into an existing vector container, you can only use the member functions provided by the vector template class, with the exception of deleting the elements of the vector container. In addition to the member functions provided by itself, you can also use some global functions.

Based on the needs of different scenarios, delete the elements of the vecotr container and use the functions (or function combinations) shown in Table 1.

Table 1 several ways to delete vector container elements
functionfunction
pop_back() Delete the last element in the vector container. The size of the container will be reduced by 1, but the capacity will not change.
erase(pos) Deletes the element at the position specified by the pos iterator in the vector container and returns the iterator pointing to the element at the next position of the deleted element. The size of the container will be reduced by 1, but the capacity will not change.
swap(beg),pop_back() First call the swap() function to exchange the location of the target element to be deleted and the last element of the container, and then use pop_back() deletes the target element.
erase(beg,end) Deletes all elements within the area specified by the iterator [beg,end) in the vector container, and returns the iterator pointing to the next element in the deleted area. The size of the container decreases, but the capacity does not change.
remove() Deletes all elements in the container equal to the specified element value, and returns an iterator pointing to the next position of the last element. It is worth mentioning that calling this function does not change the size and capacity of the container.
clear() Delete all elements in the vector container and make it an empty vector container. This function changes the size of the vector (to 0), but not its capacity.

The specific usage of these functions listed in Table 1 is explained one by one.

pop_ The use of the back () member function is very simple. It does not need to pass in any parameters and does not return a value. for instance
#include <vector>
#include <iostream>
using namespace std;

int main()
{
    vector<int>demo{ 1,2,3,4,5 };
    demo.pop_back();
    //Output dmeo container new size
    cout << "size is :" << demo.size() << endl;
    //Output demo container new capacity
    cout << "capacity is :" << demo.capacity() << endl;
    for (int i = 0; i < demo.size(); i++) {
        cout << demo[i] << " ";
    }
    return 0;
}

  


The operation result is:

size is :4
capacity is :5
1 2 3 4

It can be found that compared with the original demo container, the new demo container deletes the last element 5, and the size of the container is reduced by 1, but the capacity remains the same.

If you want to delete the element at the specified position in the vector container, you can use the {erase() member function. The syntax format of this function is:

iterator erase (pos);

Where pos is the iterator that specifies the location of the deleted element, and the function will return an iterator that points to the next location of the deleted element.

The following example demonstrates the specific usage of the erase() function:
#include <vector>
#include <iostream>
using namespace std;

int main()
{
    vector<int>demo{ 1,2,3,4,5 };
    auto iter = demo.erase(demo.begin() + 1);//Delete element 2
    //output dmeo Container NEW size
    cout << "size is :" << demo.size() << endl;
    //output demo New capacity of container
    cout << "capacity is :" << demo.capacity() << endl;
    for (int i = 0; i < demo.size(); i++) {
        cout << demo[i] << " ";
    }
    //iter The iterator points to element 3
    cout << endl << *iter << endl;
    return 0;
}

 


The operation result is:

size is :4
capacity is :5
1 3 4 5
3

It can not be seen from the results that when erase() function deletes elements, it will move the subsequent elements in the deletion position forward one after another, and reduce the size of the container by 1.

If you don't care about the order of swap() and pop () in the container, you can combine them_ The back() function can also delete the element at the specified position in the container.

Note that the swap() function is defined in the header files < algorithm > and < utility >, and one of them can be introduced when using.

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

int main()
{
    vector<int>demo{ 1,2,3,4,5 };
    //Swap the position of the element to be deleted and the last element
    swap(*(std::begin(demo)+1),*(std::end(demo)-1));//Equivalent to swap(demo[1],demo[4])
   
    //After switching positions demo container
    for (int i = 0; i < demo.size(); i++) {
        cout << demo[i] << " ";
    }
    demo.pop_back();
    cout << endl << "size is :" << demo.size() << endl;
    cout << "capacity is :" << demo.capacity() << endl;
    //output demo Elements remaining in container
    for (int i = 0; i < demo.size(); i++) {
        cout << demo[i] << " ";
    }
    return 0;
}

 


The operation result is:

1 5 3 4 2
size is :4
capacity is :5
1 5 3 4


Of course, in addition to deleting a single element in the container, you can also delete all elements in a specified area in the container. You can also use the {erase() member function. This function has two basic formats. One is introduced earlier, and the other is used here:

iterator erase (iterator first, iterator last);

Where first and last are iterators that specify the deleted element region, and the function will return an iterator pointing to a position after this region.

for instance:
#include <vector>
#include <iostream>
using namespace std;

int main()
{
    std::vector<int> demo{ 1,2,3,4,5 };
    //Delete 2 and 3
    auto iter = demo.erase(demo.begin()+1, demo.end() - 2);
    cout << "size is :" << demo.size() << endl;
    cout << "capacity is :" << demo.capacity() << endl;

    for (int i = 0; i < demo.size(); i++) {
        cout << demo[i] << " ";
    }
    return 0;
}

 


The operation result is:

size is :3
capacity is :5
1 4 5

It can be seen that, like deleting a single element, deleting an element in a specified area will also move the subsequent elements in the area forward and reduce the size of the container.

If you want to delete all elements in the container with the same value as the specified element, you can use the remove() function, which is defined in the < algorithm > header file. For example:
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    vector<int>demo{ 1,3,3,4,3,5 };
    //Swap the position of the element to be deleted and the last element
    auto iter = std::remove(demo.begin(), demo.end(), 3);

    cout << "size is :" << demo.size() << endl;
    cout << "capacity is :" << demo.capacity() << endl;
    //Output the remaining elements
    for (auto first = demo.begin(); first < iter;++first) {
        cout << *first << " ";
    }
    return 0;
}

 


The operation result is:

size is :6
capacity is :6
1 4 5

Note that after the remove() function is executed on the container, since the function does not change the original size and capacity of the container, the previous method cannot be used to traverse the container. Instead, the iterator returned by remove() needs to be used to complete the correct traversal as in the program.

The implementation principle of remove() is that when traversing the elements in the container, once the target element is encountered, mark it, and then continue traversing until a non target element is found, that is, use this element to cover the first marked position, and mark the position of the non target element at the same time, waiting for a new non target element to cover it. Therefore, if all the elements of the demo container in the above program are output, the result is 1 4 5 4 3 5.

In addition, you can also see that since multiple specified elements in the demo container are deleted through the remove() function, the size and capacity of the container have not changed, and the previously stored elements are retained in the remaining positions. We can use the erase() member function to delete these "useless" elements.

For example, modify the above program:
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    vector<int>demo{ 1,3,3,4,3,5 };
    //Swap the position of the element to be deleted and the last element
    auto iter = std::remove(demo.begin(), demo.end(), 3);
    demo.erase(iter, demo.end());
    cout << "size is :" << demo.size() << endl;
    cout << "capacity is :" << demo.capacity() << endl;
    //Output the remaining elements
    for (int i = 0; i < demo.size();i++) {
        cout << demo[i] << " ";
    }
    return 0;
}

 


The operation result is:

size is :3
capacity is :6
1 4 5

When remove() is used to delete the specified element in the container, it is often used with the erase() member function.


If you want to delete all the elements in the container, you can use the clear() member function, for example:
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    vector<int>demo{ 1,3,3,4,3,5 };
    //Swap the position of the element to be deleted and the last element
    demo.clear();
    cout << "size is :" << demo.size() << endl;
    cout << "capacity is :" << demo.capacity() << endl;
    return 0;
}

 


The operation result is:

size is :0
capacity is :6

Topics: C++ STL vector