繁体   English   中英

如何解析 char 指针字符串并将其特定部分放在 C++ 的 map 中?

[英]How can I parse a char pointer string and put specific parts it in a map in C++?

假设我有一个这样的 char 指针:

const char* myS = "John 25 Lost Angeles";

我想解析这个字符串并将其放入 hashmap 中,这样我就可以仅根据他的姓名检索该人的年龄和城市。 例子:

std::map<string, string> myMap;

john_info = myMap.find("John");

我怎样才能以优雅的方式返回 John 的所有信息? 我来自 Java 背景,我真的很想知道这是如何在 C++ 中正确完成的。 如果您可以向我展示如何使用升压 map(如果这样更容易的话),那也会很酷。 谢谢你。

我将向您展示一种使用 Boost 的方法:

住在科利鲁

#include <map>
#include <boost/fusion/adapted.hpp>
#include <boost/spirit/home/x3.hpp>
#include <iostream>
namespace x3 = boost::spirit::x3;

using Name = std::string;
struct Details {
    unsigned age;
    std::string city;
};

using Map   = std::map<Name, Details>;
using Entry = Map::value_type;

BOOST_FUSION_ADAPT_STRUCT(Details, age, city)

int main() {
    Map persons;

    std::string_view myS = //
        "John 25 Lost Angeles\n"
        "Agnes 22 Minion Appolis";

    auto name    = x3::lexeme[+x3::graph];
    auto age     = x3::uint_;
    auto city    = x3::raw[*(x3::char_ - x3::eol)];
    auto details = x3::rule<struct details_, Details>{} = age >> city;
    auto line    = name >> details;
    auto grammar = x3::skip(x3::blank)[line % x3::eol];

    if (x3::parse(myS.begin(), myS.end(), grammar, persons)) {
        for (auto& [name, details] : persons)
            std::cout << name << " has age " << details.age << "\n";
        for (auto& [name, details] : persons)
            std::cout << name << " lives in " << details.city << "\n";
    }

    // lookup:
    std::cout << "John was " << persons.at("John").age << " years old at the time of writing\n";
}

印刷

Agnes has age 22
John has age 25
Agnes lives in Minion Appolis
John lives in Lost Angeles
John was 25 years old at the time of writing

要使用哈希映射,只需替换

using Map   = std::map<Name, Details>;

using Map   = std::unordered_map<Name, Details>;

现在 output 将按实现定义的顺序排列。

警告

如果这是家庭作业,请不要使用这种(某种)方法。 很明显它是复制粘贴的。 永远不要使用你不完全理解的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM