【问题标题】:How can I parse a char pointer string and put specific parts it in a map in C++?如何解析 char 指针字符串并将其特定部分放在 C++ 中的映射中?
【发布时间】:2022-02-01 19:41:18
【问题描述】:

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

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

我想解析这个字符串并把它放在一个哈希图中,这样我就可以只根据他的名字来检索这个人的年龄和城市。示例:

std::map<string, string> myMap;

john_info = myMap.find("John");

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

【问题讨论】:

  • 使用std::stringstream。 FYU std::map 不是哈希图。
  • 你尝试了什么?你会怎么用 Java 做呢?
  • 对于哈希表,使用std::unordered_map。也就是说,您的问题似乎与两件事有关:解析字符串和存储解析的字符串。我建议删除有关哈希映射的部分并将问题集中在解析上。我强烈建议创建一个 class 来聚合信息并将字符串解析到该对象中。可能值得写一个custom operator &gt;&gt; overload

标签: c++ parsing pointers boost hashmap


【解决方案1】:

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

Live On Coliru

#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>;

现在输出将按照实现定义的顺序。

警告

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

【讨论】:

猜你喜欢
  • 2020-09-28
  • 2016-04-11
  • 1970-01-01
  • 2020-01-16
  • 2010-12-12
  • 1970-01-01
  • 2011-01-20
  • 2015-05-19
  • 2017-01-18
相关资源
最近更新 更多