2014-10-03 24 views
2

我在這裏閱讀教程代碼:https://code.google.com/p/yaml-cpp/wiki/Tutorial你如何確定你在yaml-cpp中處理的是哪種節點?

一個例子是這樣的:

YAML::Node primes = YAML::Load("[2, 3, 5, 7, 11]"); 

for (YAML::const_iterator it=primes.begin();it!=primes.end();++it) { 
    std::cout << it->as<int>() << "\n"; 
} 

而接下來的是這樣的:

YAML::Node lineup = YAML::Load("{1B: Prince Fielder, 2B: Rickie Weeks, LF: Ryan Braun}"); 

for(YAML::const_iterator it=lineup.begin();it!=lineup.end();++it) { 
    std::cout << "Playing at " << it->first.as<std::string>() << " is " << it->second.as<std::string>() << "\n"; 
} 

但是,如果交換YAML文件在這兩種情況之間,當您訪問序列的地圖迭代器或反之亦然時,將出現錯誤:

terminate called after throwing an instance of 'YAML::InvalidNode' 
what(): yaml-cpp: error at line 0, column 0: invalid node; this may result from using a map iterator as a sequence iterator, or vice-versa 

對於任意的YAML輸入,我怎樣才能確定我是否正在處理循環中的序列或映射(即我是否應該使用 - > first或不使用try/catch塊)?

我試圖尋找文檔,但我找不到它。

UPDATE

這就是我要做的:

YAML::Node config = YAML::LoadFile(filename); 

for (YAML::const_iterator it=config.begin();it!=config.end();++it) { 
    if (it->Type() == YAML::NodeType::Map) { // exception 
     std::cout << it->first.as<std::string>(); 
    } else if (it->Type() == YAML::NodeType::Sequence) { 
     std::cout << it->as<std::string>(); 
    } 
} 

但是當我運行的代碼我得到的異常如上。它編譯好。

我使用的是ubuntu 14.04(0.5.1)自帶的yaml-cpp。

回答

2

您可以

switch (node.Type()) { 
    case Null: // ... 
    case Scalar: // ... 
    case Sequence: // ... 
    case Map: // ... 
    case Undefined: // ... 
} 

或查詢明確,如:

if (node.IsSequence()) { 
    // ... 
} 

(我加了該位的教程。)

編輯:在你的具體的例子,你應該在之前檢查config.Type(),而不是任何節點的類型du響你的迭代。

+0

謝謝你的回答傑西,但我不太清楚這是如何解決我遇到的問題。我的問題是,我無法弄清楚如何獲取我可以調用這些函數的節點對象。我已經添加了我正在嘗試寫入我的問題的代碼。 – jeremy 2014-10-03 15:11:35

+0

@jeremy,我更新了你的具體例子的答案。 – 2014-10-03 15:22:42

+0

當然,這個現在有道理,謝謝! – jeremy 2014-10-03 15:44:41

相關問題