Reputation: 405
I can't figure out why I get an illegal indirection error :
#include <iostream>
#include <algorithm>
#include <stack>
#include <unordered_map>
using namespace std;
int main()
{
string s1 = "";
stack<char> s;
unordered_map<char, char> m;
m.insert('(', ')');
m.insert('{', '}');
m.insert('[', ']');
for (auto x : s1)
{
if (m.find(x) != m.end()) s.push(x);
else
{
auto it = m.find(s.top());
if (s.empty() || (it->second) != x) { cout << "Invalid\n"; s.pop(); break; }
}
}
}
it is an iterator to a map entry and I am trying to access its value.
Upvotes: 1
Views: 5501
Reputation: 15824
You have to correct your insertion into unordered_map<>
as follows:
m.insert(std::make_pair('(', ')'));
m.insert(std::make_pair('{', '}'));
m.insert(std::make_pair('[', ']'));
Demo: http://coliru.stacked-crooked.com/a/a2fff8b2f36ebc3c
A few more options for insertion into unordered_map<>
:
m.emplace('(', ')');
m.emplace('{', '}');
m.emplace('[', ']');
OR
m.insert(std::pair<char,char>('(', ')'));
m.insert(std::pair<char,char>('{', '}'));
m.insert(std::pair<char,char>('[', ']'));
EDIT
One more option:
m.emplace(std::make_pair('(', ')'));
m.emplace(std::make_pair('{', '}'));
m.emplace(std::make_pair('[', ']'));
Upvotes: 8
Reputation: 36483
There is another way to "insert" into a map that the original answer hasn't noted which is with the []
operator:
m['('] = ')';
m['{'] = '}';
m['['] = ']';
Upvotes: 4