2014-07-18 45 views
2

我正在嘗試使用boost :: variant庫創建地圖,但我似乎無法獲得地圖內任何要正確打印的數據。使用boost :: variant庫製作地圖。如何存儲和顯示適當類型的東西?

代碼:

#include <string> 
#include <iostream> 
#include "boost_1_55_0/boost/any.hpp" 
#include "boost_1_55_0/boost/variant.hpp" 
#include <map> 
#include <list> 
#include <complex> 
#include <vector> 
using namespace std; 

int main() 
{ 
    std::map <string, boost::variant <int, double, bool, string> > myMap; 
    myMap.insert(pair<string, int>("PAGE_SIZE",2048)); 
    myMap.insert(pair<string, boost::variant <int, double,bool, string> > ("PAGE_SIZE2", "hello, this is a string")); //setup an enum to specify the second value maybe? 
    cout << "data page 1: " << myMap["PAGE)SIZE1"] << "\ntype page 1: " << myMap["PAGE_SIZE"].which() << endl; 

    cout << "data: " << myMap["PAGE_SIZE2"] << "\ntype: "<< myMap["PAGE_SIZE2"].which()<< endl; 
    return 0; 

} 

忽略所有的額外包括,我一直在使用這個文件來玩弄許多不同的想法。當我與G ++編譯,我得到以下:

data page 1: 0 
type page 1: 0 
data page 2: 1 
type page 2: 2 

我得到的是,第一變量被存儲爲一個int,因此是0類型,但爲什麼它顯示爲0的值?

與第二個輸出相同的東西,除了我不明白爲什麼它被存儲爲布爾值,是值1(真)?

所有幫助表示讚賞。

謝謝!

+3

wrt示例代碼:我認爲在#include中指定boost版本目錄並不是一個好主意。將boost_1_55_0放入搜索路徑並將其從源代碼中刪除。恕我直言。 –

回答

3

第二被存儲爲bool,因爲它是比std::string一個更基本的轉換(編譯器更喜歡const char* - >boolconst char* - >std::string)。由於指針非空,它會將布爾值賦給true。您可以在此處專門構建std::string以解決默認轉換問題。

至於爲什麼數據輸出不起作用,我唯一可以懷疑的是可能設置了BOOST_NO_IOSTREAM,導致它沒有合適的operator<<

+0

謝謝,我嘗試使用const char *而不是字符串,它的工作完美。整數輸出問題實際上是一種類型。我試圖輸出一個不存在的對(myMap [「PAGE」SIZE1「]而不是myMap [」PAGE_SIZE「])。 – user2850099

相關問題