std :: map具有不同数据类型的值 [英] std::map with different data types for values

查看:109
本文介绍了std :: map具有不同数据类型的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜索论坛和Google,并且很难理解我该怎么做.

I have been searching the forums and google and having a hard time understanding how I can do what I want.

我的示例基于您在选举中看到的典型数据集.我想分割一个分隔的字符串并创建一个地图以便以后使用该字符串如下所示:名称=候选人1;投票= 1000;百分比= 10.5"

My example is based of typical dataset you see for an election. I want to split a delimited string and create a map to access later The string looks like this: "name=candidate1;vote=1000;percent=10.5"

我能够按照以下步骤创建字符串映射

I am able to create my map of strings as follows

    while (getline(oss, key, '=') && getline(oss, value))
    {

      mCanData.insert(std::pair<std::string, std::string>(key, value));

    }

我想做的,并且我不知道是否可行,是在地图中插入具有不同数据类型的值(即key ="name" value ="candidate1",key ="vote" value= 1000,键=百分比"值= 10.5).我要创建的地图将设置一个私有类变量,以后其他类可以通过getter访问该私有类变量.我无法使用boost库,因此请不要这样做.

What I would like to do, and I do not know if this is possible, is to insert the values in the map with different datatypes(i.e.key = "name" value ="candidate1", key = "vote" value =1000, key="percent" value=10.5). The map I want to create will set a private class variable that can be accessed later through a getter by other classes. I am not able to use the boost library so please do not suggest that.

任何帮助都会很大,因为我现在迷路了.如果有更好的解决方法,我也想知道.

Any help would be great as I am lost right now. If there is a better way to go about this I would like to know that as well.

推荐答案

如果您确实想在地图中放置非结构化数据,则在C ++ 17中,可以使用 std :: variant 执行此操作,然后访问以获取您的数据.
它遵循一个最小的有效示例:

If you really want to put not structured data in your map, in C++17 you can use std::variant to do that and thus visit it to get back your data.
It follows a minimal, working example:

#include <variant>
#include <string>
#include <map>
#include <iostream>

int main() {
    std::map<std::string, std::variant<std::string, int, double>> mm;
    mm["name"] = "candidate1";
    mm["vote"] = 1000;
    mm["percent"] = 10.5;

    auto visitor = [](auto data){ std::cout << data << std::endl; };
    std::visit(visitor, mm["name"]);
    std::visit(visitor, mm["vote"]);
    std::visit(visitor, mm["percent"]);
}

wandbox .
是否适合您主要取决于您是否可以使用C ++ 17.您没有指定它,所以很难说.

See it up and running on wandbox.
If it works for you mostly depends on the fact that you can use or not C++17. You didn't specify it, so it's hard to say.

话虽这么说,结构化数据(如@rici所建议的)似乎是解决该问题的一种更好的方法.
但是,我们既不能说出真正的问题是什么,也不能说出其余代码的设计方式,所以值得一提的是 std :: variant .

That being said, structured data (as suggested by @rici) looks like a far better solution to the problem.
However we cannot say neither what's the real problem nor how you designed the rest of the code, so it's worth it mentioning also std::variant probably.

这篇关于std :: map具有不同数据类型的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆