您的位置:首页 > 其它

vector list map 遍历删除指定元素

2017-05-10 16:15 666 查看
#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("\n");
}

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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: