0

Here is the thing, I have several std::maps, like this:

std::map<int, std::set> map_1; std::map<int, std::string> map_2; std::map<int, long> map_3; ... 

And there are also several numbers, each of which relates to one map listed above, like

1 -> map_2 2 -> map_1 3 -> map_3 ... 

What I'm trying to do is that, put all the maps into one array, then access each number's map will be like accessing the element of that array, like this:

arr = [map_2, map_1, map_3]; // let x be a number map_x = arr[x]; do_something(map_x) 

This way, I can relieve myself of writing switch...case, right?

But can I put them together and how?

10
  • 4
    What for do you need it? Seems to me better to change your design. Commented Nov 6, 2012 at 8:52
  • @DenisErmolin, well, I'm just trying to avoid writing switch...case... Commented Nov 6, 2012 at 8:53
  • write an op[] and hide the switch in it Commented Nov 6, 2012 at 8:54
  • 2
    How were you planning on declaring map_x and do_something() so that the assignment would work for all of the array elements? Commented Nov 6, 2012 at 9:04
  • 2
    You are trying to reinvent polymorphism... Commented Nov 6, 2012 at 9:57

2 Answers 2

1

The right way to do things like this is with classes. Create a base class map, and templated subclasses for the specific types of maps. Then you can create an array of map* elements.

Sign up to request clarification or add additional context in comments.

Comments

0

Yet another solution is to use boost::variant.

Put all your map types into variant (boost::variant<std::map<int, std::set>, std::map<int, std::string>, std::map<int, long>>), then write visitor like (do_something should be already overloaded, right?):

class do_something_visitor : public boost::static_visitor<> { public: template <typename T> void operator()(T &map) const { do_something(map); } }; 

Then apply visitation (boost::apply_visitor) over items in your array of variants.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.