#include <iostream> #include <vector> using namespace std; int main() { std::vector<int> ve1; ve1.push_back(1); ve1.push_back(2); ve1.push_back(3); ve1.push_back(4); ve1.push_back(5); ve1.push_back(6); std::vector<int>::iterator it; cout<<"删除前的元素:"; for (it=ve1.begin();it!=ve1.end();++it) { cout<<" "<<*it; } cout<<endl; // 这里移除的算法复杂度是O(1),将待删除元素与最后一个元素交换再pop_back int idx=0; if (static_cast<size_t>(idx) == ve1.size()-1) { ve1.pop_back(); } else { iter_swap(ve1.begin()+idx, ve1.end()-1); ve1.pop_back(); } cout<<"删除后的元素:"; for (it=ve1.begin();it!=ve1.end();++it) { cout<<" "<<*it; } cout<<endl; system("pause"); return 0; }
删除vector中元素高效的方法,布布扣,bubuko.com
时间: 2024-10-13 12:33:37