C++ vector 删除
时间: 2023-09-29 08:10:01 浏览: 91
C++中可以使用vector的erase()函数来删除元素。erase()函数接受一个迭代器参数,该参数指向要删除的元素。以下是一个简单的示例代码:
```
#include <iostream>
#include <vector>
using namespace std;
int main() {
// 创建一个vector
vector<int> myVec = {1, 2, 3, 4, 5};
// 打印vector中的所有元素
cout << "Original vector: ";
for (int i : myVec) {
cout << i << " ";
}
cout << endl;
// 删除第三个元素
myVec.erase(myVec.begin() + 2);
// 打印删除后的vector
cout << "Modified vector: ";
for (int i : myVec) {
cout << i << " ";
}
cout << endl;
return 0;
}
```
在这个例子中,我们首先定义了一个包含5个元素的vector。然后使用erase()函数删除了第三个元素(索引为2)。最后,我们打印出删除后的vector。<em>1</em><em>2</em><em>3</em>
#### 引用[.reference_title]
- *1* [在C++中,如何把vector中的某一项删除](https://blog.csdn.net/Ausma/article/details/129489549)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
- *2* [C++中vector中删除/添加指定位置处的元素](https://blog.csdn.net/qq_32867925/article/details/125793866)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
- *3* [谈谈C++中vector的删除](https://blog.csdn.net/lishichengyan/article/details/82669153)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
[ .reference_list ]
阅读全文