Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map with different data types for values

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

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

    }

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.

like image 286
baruti Avatar asked Nov 21 '17 03:11

baruti


1 Answers

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"]);
}

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.


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.

like image 94
skypjack Avatar answered Sep 29 '22 18:09

skypjack