vector的逆序删除

#include <iostream>
#include <vector>
#include <set>
using namespace std;
int main() {
vector<int>test = { 1,2,2,2,3,4,2,3,2,2,63,2,99,2,2,1};
for (auto it = test.rbegin(); it != test.rend();)
{
if (*it == 2)
{ // 删除值为2的元素
int index = test.rend() - it - 1; // 通过反向迭代器计算出索引
it++; // 向前走一步
test.erase(test.begin() + index); // 通过迭代器来删除元素
} else {
it++;
}
}
for (auto it = test.begin(); it != test.end(); it++) {
cout << *it << " ";
}
return 0;
}

  

posted @ 2023-12-04 09:01  我微笑不代表我快乐  阅读(12)  评论(0编辑  收藏  举报