I've been shown how to create a jagged multidimensional std::map
by using boost::any
.
However, I'm having trouble setting the values like in this answer.
When I use
accounts["bank"]["cash"] = 100;
gcc
gives this error
error: no match for ‘operator[]’ in ‘accounts.std::map<_Key, _Tp, _Compare,
_Alloc>::operator[]<std::basic_string<char>, boost::any,
std::less<std::basic_string<char> >, std::allocator<std::pair<const
std::basic_string<char>, boost::any> > >((* & std::basic_string<char>(((const
char*)"bank"), (*(const std::allocator<char>*)(& std::allocator<char>())))))["cash"]’
How can a jagged multidimensional map
created with boost::any
be accessed? (If there is a better technique to do this, please show me. I only care about what works and is quick to write.)
multidimensional declaration
std::map<std::string, boost::any> accounts;
accounts["bank"] = std::map<std::string, boost::any>();
accounts["bank"]["cash"] = 100;
I gave up and tried to use json-spirit's mObject
instead since all of this seems already built in.
Funny thing is is that with the exact same notation, I get the exact same error.
Of course this cause compile time error, you put to boost::any std::map, but compiler have no idea about this. accounts["bank"] has "boost::any" type, and boost::any have no
Read how boost::any works: http://www.boost.org/doc/libs/1_54_0/doc/html/any/s02.html
Fix is trivial:
How did you define your accounts map? As boris said, you need to nest two maps together in order to do what you want.
Replace the type string with boost::any
How does this work?
accounts["bank"] returns the value of the outermost map, which corresponds to
accounts["bank"]["cash"] returns the value of the innermost map, which corresponds to
Defining a 1 dimensional map does not allow you to do what you want, but 2 dimensional maps do.