C++容器之动态数组vector②

5、小作业:
定义一个 int 类型的 vector 动态数组,将以下元素:1, 4, 3, 7, 9, 3, 6, 8, 3, 5, 2, 3, 7 插入到动态数组中。之后,使用 for 循环删除动态数组中的值为 3 的元素,并将结果输出出来!

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int temp[] = { 1, 4, 3, 7, 9, 3, 6, 8, 3, 5, 2, 3, 7 ,9,3,3,3,3,3,3,3,3,3,3,8,0,8,3,8};
    vector<int> a_int;

    a_int.insert(a_int.begin(),temp,temp + sizeof(temp)/sizeof(int));

    //for (int idx = 0; idx < a_int.size(); idx++)
    //{
    //    if (a_int[idx] == 3)
    //    {
    //        a_int.erase(a_int.begin() + idx);
    //        idx--;
    //    }
    //    else
    //    {
    //        cout << a_int[idx];
    //    }

    //}
    //cout << endl;

    vector<int>::iterator itor;
    for (itor = a_int.begin(); itor != a_int.end(); itor++)
    {
        if (*itor == 3)
        {
            itor = a_int.erase(itor);
            itor--;
        }
        else
        {
            cout << *itor;
        }
    }
    cout << endl;
    return 0;
}

 

posted on 2021-01-15 15:36  SakuraQAQ  阅读(74)  评论(0)    收藏  举报

导航