How to loop through a map of vectors?

Hello! I have a map of vectors (integer keys) and I want to be able to loop through the map AND also through each vector but I'm not sure how to start the vector iteration. Here's what I have so far

1
2
3
4
5
6
7
double my_function(const map<int, vector<double>>& MAP) {
	for (auto it1 = MAP.begin(); it1 != MAP.end(); ++it1) {
		for (auto it2 = MAP[*it1].begin() .... ) {// this is the line I have trouble with
    // do stuff here
		}
	}
}


Thanks!
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <vector>
#include <map>

int main()
{
    const std::map< int, std::vector<double> > map =
    {
        { 247, { 1.2, 2.3, 3.4, 4.5 } },
        { 106, { 5.6, 6.7, 7.8, 8.9, 9.1, 1.2, 2.3 } },
        { 184, { 3.4, 4.5 } }
    };

    {
        // option 1: range-based loops
        for( const auto& pair : map )
        {
            std::cout << "key: " << pair.first << "  value: [  " ;
            for( double d : pair.second ) std::cout << d << "  " ;
            std::cout << "]\n" ;
        }
    }
    std::cout << "----------------\n" ;
    {
        // option 2: iterators
        for( auto map_iter = map.cbegin() ; map_iter != map.cend() ; ++map_iter )
        {
            std::cout << "key: " << map_iter->first << "  value: [  " ;
            for( auto vec_iter = map_iter->second.cbegin() ; vec_iter != map_iter->second.cend() ; ++vec_iter )
                std::cout << *vec_iter << "  " ;
            std::cout << "]\n" ;
        }
    }
    std::cout << "----------------\n" ;
    {
        // option 3: range-based loop for map, subscript operator for vector
        for( const auto& pair : map )
        {
            std::cout << "key: " << pair.first << "  value: [  " ;
            for( std::size_t i = 0 ; i < pair.second.size() ; ++i )  std::cout << pair.second[i] << "  " ;
            std::cout << "]\n" ;
        }
    }
    
    // options 4, 5 ...
}

http://coliru.stacked-crooked.com/a/bfa79466126a8cf4
Using first/ second would have been helpful! Thanks :D
Morning my friend, before giving you more of a hint, I have to let you know iterating through a map is a bit slower than iterating through a vector, and if you have a simple int index, you may actually want to have a multidimensional vector instead of a map of vectors.

Now, as for iterating through a vector, the typical method is just like moving through an array:

1
2
3
for(int a = 0; a < vecname.size(): a++){
    dosomethingwith(vecname[a]);
}


In your case, you're making it a bit complicated by using iterators, but that is generally not a terrible way of doing things. you can use it1->second to get the vector from the iterator, instead of MAP[*it1]

Example:

for (auto it2 = it1->second.begin(); it2 != it1->second.end(); it2++ )
Last edited on
Topic archived. No new replies allowed.