2012-11-06 94 views
0

這裏的東西,我有幾個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 
... 

我「M試圖做的是,把所有的地圖到一個數組,然後訪問每個號碼的地圖 會像訪問該數組的元素,像這樣:

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

這樣,我可以減輕自己的寫作switch...case,對吧?

但是我可以把它們放在一起嗎?

+4

你需要什麼?似乎更好地改變你的設計。 –

+0

@DenisErmolin,好吧,我只是想避免寫'switch ... case ...' – Alcott

+0

寫一個op []並隱藏它的開關 –

回答

1

做這種事情的正確方法是使用類。爲特定類型的地圖創建一個基類map和模板化的子類。然後你可以創建一個map*元素的數組。

0

另一種解決方案是使用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)在項目的變量數組中。

相關問題