Pergunta

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.

Foi útil?

Solução

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;
}

Outras dicas

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

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main()
{
    map<string, map<string, string>> accounts;

    accounts["bank"]["cash"] = "infinity";

    cout << accounts["bank"]["cash"];

    return 0;
}

How does this work?

  • Maps are key and value pairs.

accounts["bank"] returns the value of the outermost map, which corresponds to

map<string, **map<string, string>**>

accounts["bank"]["cash"] returns the value of the innermost map, which corresponds to

map<string, map<string, **string**>>

Defining a 1 dimensional map does not allow you to do what you want, but 2 dimensional maps do.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top