从 Vector 生成类数据成员

2024-02-28

请考虑这个 C++ 问题:

#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

class ParseURL{
    private:
        int qualify; // 0 means we qualify
    public:
        string node;
        string service;
        bool primary;
        bool health;
        string epoch;
        // methods
        ParseURL(string URL);
        ~ParseURL();
};


ParseURL::ParseURL(string URL){
    vector<string> g2 = {"node", "service", "primary", "health", "epoch"};

    for (string tag : g2){
        auto found = URL.find(tag);
        if ( found != string::npos ){
            auto cut_from = found + 1 + tag.size() ;
            auto meh = URL.substr(cut_from, URL.substr(cut_from).find("&") );
            // is there a way we can avoid these lines below?
            if (tag.find("node",0) == 0){
                this->node = meh;
            } else if (tag.find("service",0) == 0 ){
                this->service = meh;
            } else if (tag.find("epoch",0) == 0) {
                this->epoch = meh;
            } else if (tag.find("health",0) == 0){
                this->health = (meh == "OK");
            } else if (tag.find("primary",0) == 0 ){
                this->primary == (this->node == meh);
            }
        }
    }

}

ParseURL::~ParseURL(){
    cout << "Tearing Down the class\n";
}
int main(){
    char req[] = "GET /register?node=hostrpi3&service=potatoservice&primary=node1&health=OK&epoch=1559345106 HTTP";
    string Request = req;
    Request = Request.substr(Request.find_first_of(" ") );
    Request = Request.substr(0, Request.find(" HTTP"));
    ParseURL *a = new ParseURL(Request);

    cout.width(12);
    cout << "a->node: " << a->node << endl;
    cout.width(12);
    cout << "a->service: " << a->service << endl;
    cout.width(12);
    cout << "a->epoch: " << a->epoch << endl;
    cout.width(12);
    cout << "a->health: " << a->health << endl;
    cout.width(12);
    cout << "a->primary: " << a->primary << endl;

    delete(a);

    return 0;
}

我需要表示一个基于 URL 查询字符串的对象,我需要的标签以向量 g2 表示,正如您所看到的,我为ParseURL从这些标签中。

O/P 看起来像:

   a->node: hostrpi3
a->service: potatoservice
  a->epoch: 1559345106
 a->health: 1
a->primary: 0
Tearing Down the class

虽然这个版本可以用,但感觉还可以改进很多。尽管这一切都在 Vector 中,但我还是反复做tag.find对于每个属性。我希望一定有更好的方法。你能指出正确的方向吗?谢谢!

Edit 1

谢谢,我按照建议更新了构造函数:

ParseURL::ParseURL(string URL){
    char tags[10][100] = {"node", "service", "primary", "health", "epoch"};

    int i = 0;
    for (auto tag : tags){
        auto found = URL.find(tag);
        if ( found != string::npos ){
            auto cut_from = found + 1 + strlen(tag);
            auto tag_info = URL.substr(cut_from, URL.substr(cut_from).find("&") );
            switch (i){
                case 0:
                    this->node = tag_info; 
                    break;
                case 1:
                    this->service = tag_info; 
                    break;
                case 2:
                    this->primary = (this->node == tag_info); 
                    break;
                case 3:
                    this->health = (tag_info == "OK"); 
                    break;
                case 4:
                    this->epoch = tag_info; 
                    break;
            }
        }
    i++;
    }
}

例如,bash 提供变量的间接引用 - 也就是说,一个变量可能包含另一个变量的名称:

$ cat indirect.sh 
#!/bin/bash 

values="value1 value2"
value1="this is value1"
value2="this is value2"

for i in $values; do 
    echo "$i has value ${!i}"
done

$ ./indirect.sh 
value1 has value this is value1
value2 has value this is value2

我希望类似的情况也存在,尽管如此,我在这里学到了宝贵的教训。谢谢你!


假设您想要保留不同的类成员(而不是一个键值存储),您can使用字符串和指向成员的指针的静态表:

vector<pair<string,string ParseURL::*>> keys={{"node",&ParseURL::node},…};

但这在这里不起作用,因为类型不同,而且每种类型的处理也不相同。相反,对于这种几乎并行,语法上的最佳选择通常是lambda:

const auto get=[&URL](const string &tag) {
  auto found = URL.find(tag);
  if(found == string::npos) return "";
  auto cut_from = found + 1 + tag.size() ;
  return URL.substr(cut_from, URL.substr(cut_from).find("&") );
};
node=get("node");
service=get("service");
epoch=get("epoch");
health=get("health")=="OK";
primary=get("primary")==node;

这种风格的优点是可以明确初始化health and primary。通过对私有构造函数进行足够的扭曲,可以将其放入成员初始值设定项列表中,这是更好的做法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 Vector 生成类数据成员 的相关文章

随机推荐

  • 变量未在 PHP 循环中传递/更新

    所以基本上我正在做的是创建 php 脚本 该脚本打印表格并根据表单中输入的内容更新和计算值 所以我有一个单独的 HTML 文件 其中包含表单 它传递 3 个变量 tempStart tempEnd windSpeed 然后我创建了一个在表的
  • 在 Eclipse 帮助中搜索 RCP 未返回任何结果

    我有一个 RCP 应用程序 并在菜单上启用了帮助 我能够成功调出我创建的帮助 但是 当我输入搜索词时 没有返回结果 需要什么才能从 Eclipse 帮助引擎搜索我的帮助内容 解决方案是使用帮助内容更新插件的版本号以重建索引 我依赖 qual
  • VS2010 构建后事件,替换文件中的字符串。电源外壳?

    在 VS2010 中成功构建后 我需要替换缩小的 js 文件中的简单字符串 因此 我尝试从 构建后事件 窗口运行一个简单的命令行调用 这个例子 来自这里 https blogs technet com b heyscriptingguy a
  • Polymer 中的横向通信

    问题是这样的 任何两个聚合物元素都可能需要通信 没有假设这些元素可能位于 DOM 或影子 DOM 中的位置 这意味着一个事件不能简单地冒泡到另一个元素 实现这一点的好旧方法是让事件冒泡到根节点 然后触发播送根节点上的事件供其他元素监听 然而
  • 如何在sklearn中找到多个节点的最近邻居?

    所以基本上我正在开发一个推荐系统 其中用户可以选择多个电影 节点 并给出与用户选择的所有电影 节点 相似的推荐 为了做到这一点 我需要同时找到这些多个节点的最近邻居 即结果应该接近node1 and node2 我怎样才能做到这一点 X 0
  • 构建规则中的 Bazel 环境变量

    我想参考 DirectX SDKBUILD文件 问题是 据我所知 Bazel 仅支持通过 action env DXSDK DIRBazel 的参数 它应该在动作中使用 必须在插件中定义 bzl file 有没有更简单的方法通过将环境变量用
  • 如何从给定索引列表的 std::vector 中删除项目

    我有一个项目向量items 以及应该从中删除的索引向量items std vector
  • GIDSignIn 钥匙串错误 iOS 10 Xcode 8

    在 iOS 10 和 xcode 8 中 当我尝试登录 google 服务时 我得到 钥匙串错误 func sign signIn GIDSignIn didSignInFor user GIDGoogleUser withError er
  • 从 jQuery UI 对话框内部的元素关闭它?

    这是一个简单的问题 可能比我想象的要简单 我正在使用 ajax 调用生成的 html 填充 jQuery UI 对话框 在某些情况下 html 包含一个按钮 单击该按钮时 我想关闭包含的对话框 假设我对指定为对话框的元素一无所知 eleme
  • 从 Drools 6 中的数据库加载和更新规则

    如何在启动时从数据库表加载规则并从 Drools 6 2 0 中的同一个表更新它们 我找到了一个example http sujitpal blogspot com 2013 03 jboss rules in database take
  • 如何在 Mac 上从 ifconfig 获取格式为“接口:IP 地址”的输出

    我试图从 ifconfig 中获取以下格式化输出 en0 10 52 30 105 en1 10 52 164 63 我至少能够弄清楚如何使用以下命令获取 IP 地址 淘汰 localhost 但这不足以满足我的要求 ifconfig gr
  • JSON @属性

    我很难理解如何读取包含 attributes 的 JSON 对象 JavaScript ajax type GET dataType json url http script weather php r req success functi
  • 如何使用正则表达式过滤字符串中不需要的字符?

    基本上 我想知道是否有一个方便的类或方法来过滤字符串中不需要的字符 该方法的输出应该是 已清理 的字符串 IE String dirtyString This contains spaces which are not allowed St
  • 如何从 Pl/SQL 写入文本文件,PLS 错误 00363

    我正在尝试从过程写入文件 out File Utl File FOpen C test batotest txt W Utl File Put Line out file Hi this is text file Utl File FClo
  • 从 powershell 运行 SQL 脚本文件

    我正在尝试从 PowerShell 运行存储在文本文件中的查询 我使用以下方法来做到这一点 Invoke Expression sqlcmd d TestDB U user P pw i E SQLQuery1 sql 如果在执行查询时发生
  • equals 方法未在定义类的对象上使用[重复]

    这个问题在这里已经有答案了 抱歉 已经很晚了 所以我可能无法解释所有细节 但我一直在研究这个问题 但我无法理解为什么数组中的对象 Item 对象引用不使用它所给出的 Item 类的 equals 方法 我检查了函数内两个 Item 对象的类
  • 更有效地查找和压缩数百万个文件

    我的服务器上有一个作业在命令行提示符下运行了两天 find data name filepattern 2009 exec tar uf 2009 tar 它正在采取forever 然后还有一些 是的 目标目录中有数百万个文件 在经过良好哈
  • 如何将完整的文件夹结构上传到 Artifactory 存储库到新文件夹并保持文件夹名称不变?

    我是自动化新手 尝试将整个文件夹结构以及父文件夹和子文件夹上传到 Artifactory 存储库 结构如下 test1 文件夹包含子文件夹 new ref 还包含子文件夹 gt gt v1 new data1 还包含子文件夹 gt gt v
  • 什么时候应该在JavaScript中使用outerHTML? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 何时应使用innerHTML 和outerHTML 有什么区别 您将如何最好地实现outerHTML 来替换或添加内容 externa
  • 从 Vector 生成类数据成员

    请考虑这个 C 问题 include