• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LOFLY
终其一生,编织快乐
博客园    首页    新随笔    联系   管理    订阅  订阅

补充

1. 使用vector删除偶数

#include <iostream>
using namespace std;
#include <vector>

void removeEven(vector<int> &num)
{
    vector<int>::iterator it;

    for(it = num.begin(); it!=num.end();it ++)
    {
        if(*it % 2 == 0)
        {
           num.erase(it);
           it --;
        }
    }
}

int main(int argc, char const *argv[])
{
    vector<int> num{1,2,3,4,5,6};
    removeEven(num);
    for(int a : num)
    {
        cout << a << " ";
    }
    cout << endl;
    return 0;
}

这里需要注意的地方,使用erase函数时,删除一个元素,后面元素就会自动向前移动一个位置,所以说上面代码中使用了it--, 因为下一个元素就在当前删除的这个元素的位置。
posted @ 2022-12-12 20:30  编织快乐  阅读(61)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3