[英]How to iterate through a map of vectors while deleting?
I have a map of vectors in C++. 我在C ++中有矢量地图。 For each vector, I'd like to delete entries that meet a certain condition. 对于每个向量,我想删除符合特定条件的条目。 If a vector ends up empty, I'd like to delete it from the map. 如果向量最终为空,我想将其从地图中删除。 I know deletion can mess up iterators, and doubly iterating makes this even more confusing for me. 我知道删除操作可能会使迭代器混乱,而双重迭代会使我感到更加困惑。 What's the best way to accomplish this? 做到这一点的最佳方法是什么?
The standard mutating container loop: 标准的变异容器循环:
for (auto it = m.begin(); it != m.end(); )
{
// work
if (/* need to delete */) // e.g "if (it->second.empty())"
{
it = m.erase(it);
}
else
{
++it;
}
}
Here is a demonstrative program that shows how it can be done 这是一个演示程序,展示了如何完成
#include <iostream>
#include <map>
#include <vector>
int main()
{
std::map<int, std::vector<int>> m =
{
{ 1, { 1, 2 } },
{ 2, { 2 } },
{ 3, { 3, 4 } },
{ 4, { 4 } }
};
for ( const auto &p : m )
{
std::cout << p.first << ": ";
for ( int x : p.second ) std::cout << x << ' ';
std::cout << std::endl;
}
for ( auto it = m.begin(); it != m.end(); )
{
it->second.erase( it->second.begin() );
if ( it->second.empty() ) it = m.erase( it );
else ++it;
}
std::cout << std::endl;
for ( const auto &p : m )
{
std::cout << p.first << ": ";
for ( int x : p.second ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
The program output is 程序输出为
1: 1 2
2: 2
3: 3 4
4: 4
1: 2
3: 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.