可以将不同类型的对象放入一个数组中
can different types of objects be put in one array?
这是我的几个std::map
S,例如:
std::map<int, std::set> map_1;
std::map<int, std::string> map_2;
std::map<int, long> map_3;
...
还有几个数字,每个数字都与上面列出的一个映射有关,例如
1 -> map_2
2 -> map_1
3 -> map_3
...
我要做的是,将所有地图都放入一个数组中,然后访问每个数字的地图就像访问该数组的元素一样,如下:
arr = [map_2, map_1, map_3];
// let x be a number
map_x = arr[x];
do_something(map_x)
以这种方式,我可以放松自己写switch...case
,对吗?
但是我可以将它们放在一起吗?
进行类似类的正确方法。创建基类map
,并为特定类型的地图类型的模板子类创建模板。然后,您可以创建map*
元素的数组。
另一个解决方案是使用boost :: variant。
将所有地图类型都放入变体中(boost::variant<std::map<int, std::set>, std::map<int, std::string>, std::map<int, long>>
),然后写下访问者(do_something
应该已经重载,对吗?):
class do_something_visitor
: public boost::static_visitor<>
{
public:
template <typename T>
void operator()(T &map) const
{
do_something(map);
}
};
然后,将访问(boost::apply_visitor
)对变体中的项目应用。