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

时间秒杀一切 提交于 2019-12-24 19:37:57

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/18808339/set-access-jagged-map-values-made-with-mapstring-boostany

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!