如何使用boost有效地从std :: string反序列化nvp字典

时间:2016-02-29 11:12:51

标签: dictionary boost

假设我有一个名称 - 值对字典的字符串表示,其中名称/值和名称 - 值对之间有自定义分隔符,例如: “foo:4 | bar:-1”或“Alice => cat; Bob => dog”。 它可以通过boost的split()完成,但我很好奇,如果首先,这样做不仅仅是重新发明轮子,其次,有更有效的替代方案,如一些定制的反序列化。

1 个答案:

答案 0 :(得分:1)

考虑使用Boost Spirit。使用您编写的X3版本

const std::string input = "foo:4|bar:-1"; // or "Alice=>cat;Bob=>dog";

auto text = +~x3::char_(":|");

std::map<std::string, int> parsed;
if (parse(input.begin(), input.end(), (text >> ':' >> x3::int_) % '|', parsed)) {
    std::cout << "parsed[bar]: " << parsed["bar"]  << "\n";
}

<强> Live On Coliru

另一种形式:

const std::string input = "Alice=>cat;Bob=>dog";

auto text = +(x3::char_ - ';' - "=>");

std::map<std::string, std::string> parsed;
if (parse(input.begin(), input.end(), (text >> "=>" >> text) % ';', parsed)) {
    std::cout << "parsed[Bob]: " << parsed["Bob"]  << "\n";
}

<强> Live On Coliru