Search code examples
c++iteratorstdvectorstdmap

How to iterate map<int, vector <int>>?


I have map<int, vector > like this:

#include <iostream>
#include <map>
#include <vector>

using namespace std;

int main() {
    
    map<int, vector <int>> someMap;
    someMap[5] = {5, 2, 3, 7};
    someMap[151] = {5, 9, 20};

    return 0;
}

I need to find the last vector element in each map value. Output must be like this:

7
20

Thanks :)


Solution

  • You can use the std::vector::back member function as shown below:

    #include <iostream>
    #include <map>
    #include <vector>
    #include <cassert>
    using namespace std;
    
    int main() {
        
        map<int, vector <int>> someMap;
        someMap[5] = {5, 2, 3, 7};
        someMap[151] = {5, 9, 20};
        //iterate through each element of the map
        for(const std::pair<int, std::vector<int>> &myPair: someMap)
        {
            //make sure the vector is not empty
            assert(!myPair.second.empty());
            
            //print the last element in the vector
            std::cout << myPair.second.back() <<std::endl;
        }
        return 0;
    }
    

    The output of the above program is:

    7
    20
    

    which can be seen here.