Iterate through an array of unordered_map in C++

In my program, I intend to use array of unordered_map but fail in traversing through it. I initialize it as below:

1
2
3
4
5
6
7
8
9
10
11
unordered_map<string,bool> mp[m];
  for(int i=0;i<m;i++){
        int l;
        cin>>l;
        for(int j=0;j<l;j++){
            string s;
            cin>>s;
            mp[i].emplace(s,true);
        }
        
    }


However, when I atempt to access an element of array(such as mp[0]) and print its children element, I get "the Process returned -1073741819 (0xC0000005)".
1
2
for(auto &it: mp[0])
        cout<<it.first<<"\n";

What's the proper way to solve this problem?
Last edited on
shudders at the use of l as a variable name

Please show a minimal, but compilable example that reproduces the behavior you mention.

How does the following program behave for you:

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
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;

int main()
{
	const int m = 3;
	unordered_map<string,bool> mp[m];
	
	for (int i = 0; i < m; i++){
		int num_items;
		cout << "Num items in map " << (i + 1) << ": ";
		cin >> num_items;
	
		for(int j = 0; j < num_items; j++){
			string s;
			cout << "Map entry: ";
			cin >> s;
			mp[i].emplace(s, true);
		}
	}
	
	for(auto &it : mp[0]) // note: better to be const auto&
		cout << it.first << "\n";
}


Num items in map 1: 2
Map entry: hello
Map entry: world
Num items in map 2: 5
Map entry: goodbye
Map entry: cruel
Map entry: world
Map entry: it's
Map entry: over
Num items in map 3: 3
Map entry: walk
Map entry: on
Map entry: by
world
hello
Last edited on
Topic archived. No new replies allowed.