Home  >  Article  >  Backend Development  >  How to remove elements from C++ STL container?

How to remove elements from C++ STL container?

WBOY
WBOYOriginal
2024-06-02 11:29:57205browse

In C++ STL, the following methods can be used to remove elements from different containers: Remove from vector: use iterator or index. Remove from list: use iterator. To remove from a set: Use the erase() method whose value is the element to be removed. Delete from the map: Use the erase() method with the key value of the element to be deleted.

如何从C++ STL容器中删除元素?

How to remove elements from a C++ STL container

In the C++ Standard Template Library (STL), there are several containers available to organize data. These containers support various operations, including deleting elements. This article will describe various methods of removing elements from different types of STL containers.

Remove elements from vector

To remove elements from a vector, you can use one of the following methods:

// 使用迭代器
vector<int> vec;
vec.push_back(10);
vec.push_back(20);
vec.erase(vec.begin() + 1); // 删除 vec[1]

// 使用索引
vec.erase(vec.begin(), vec.begin() + 1); // 删除 vec[0]

Remove elements from list

To remove elements from the list, you can use the following methods:

list<int> lst;
lst.push_back(10);
lst.push_back(20);
lst.erase(lst.begin()); // 删除第一个元素

Remove elements from set

To remove elements from the set , you can use the following method:

set<int> st;
st.insert(10);
st.insert(20);
st.erase(10); // 删除值为 10 的元素

Delete elements from map

To delete elements from the map, you can use the following method:

map<int, string> mp;
mp.insert(pair<int, string>(10, "Hello"));
mp.insert(pair<int, string>(20, "World"));
mp.erase(10); // 删除具有 key 为 10 的元素

Practical Case:

Consider an application that tracks student performance in academic courses. The application uses STL containers to store students and their grades. The following example shows how to delete students and their grade records from a container:

map<string, int> student_成績;
student_成績.insert(pair<string, int>("John", 90));
student_成績.insert(pair<string, int>("Mary", 80));

// 从映射中删除 John 的记录
student_成績.erase("John");

With the above method, elements can be deleted from various STL containers easily and efficiently.

The above is the detailed content of How to remove elements from C++ STL container?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn