简体   繁体   中英

How to iterate through a map of vectors while deleting?

I have a map of vectors in 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM