c++dictionaryjagged-arraysboost-anyjson-spirit

set/access jagged map values made with map<string, boost::any>


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;

json-spirit

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.


Solution

  • std::map<std::string, boost::any> accounts;
    accounts["bank"] = std::map<std::string, boost::any>();
    accounts["bank"]["cash"] = 100;
    

    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

    int& operator[](const char *)
    

    Read how boost::any works: http://www.boost.org/doc/libs/1_54_0/doc/html/any/s02.html

    Fix is trivial:

    #include <boost/any.hpp>
    #include <map>
    #include <string>
    
    int main()
    {
      std::map<std::string, boost::any> accounts;
      accounts["cash"] = 100;
      accounts["bank"] = std::map<std::string, boost::any>();
      boost::any_cast<std::map<std::string, boost::any> &>(accounts["bank"])["cash"] = 100;
    }