vector list map 遍历删除指定元素

#include <stdio.h>
#include <stdint.h>
#include <vector>
#include <list>
#include <map>

template<typename T>
void Dump(const T &s)
{
    for (T::const_iterator it = s.begin(); it != s.end(); ++it)
    {
        printf("%d ", *it);
    }
    printf("
");
}

void DelVector()
{
    std::vector<int32_t> vec{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Dump(vec);
    for (auto it = vec.begin(); it != vec.end();)
    {
        if (*it % 2 == 0)
        {
            it = vec.erase(it);
        }
        else
        {
            ++it;
        }
    }
    Dump(vec);
}

void DelList()
{
    std::list<int32_t> ls{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Dump(ls);
    for (auto it = ls.begin(); it != ls.end();)
    {
        if (*it % 2 == 0)
        {
            it = ls.erase(it);
        }
        else
        {
            ++it;
        }
    }
    Dump(ls);
}

void DelMap()
{
    std::map<int32_t, int32_t> map{ { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 }, { 6, 7 }, { 7, 8 }, { 8, 9 }, { 9, 10 } };
    Dump(map);
    for (auto it = map.begin(); it != map.end();)
    {
        if (it->first % 2 == 0)
        {
            it = map.erase(it);
        }
        else
        {
            ++it;
        }
    }
    Dump(map);
}

int32_t main()
{
    DelVector();
    DelList();
    DelMap();
    getchar();
    return 0;
}

原文地址:https://www.cnblogs.com/tangxin-blog/p/6836525.html