Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Having trouble making a map with different types

I want to make a map that has string keys that have string values and with the second data type being string keys with a list value.

I tried following the solutions mentioned under this thread: Store multiple types as values in C++ dictionary? but I keep on getting these errors. Any help is appreciated, I’ve been at this for quite some time.

'variant' is not a member of 'std'
even though I have it included on top

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

template argument 1 is invalid
on the string syntax

no operator "=" matches these operands on the equal signs


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

typedef std::map<std::variant<std::string, std::list<std::string>>, std::variant<std::string, std::string>> Dict;

int main(){
    std::list<std::string> List1 {"Teamwork", "Hate"};
    Dict d;
    d["TIME"] = "8:15";
    d["TAGS"] = List1;

    return 0;
}


>Solution :

std::map<std::variant<std::string, std::list<std::string>>, std::variant<std::string, std::string>>

Is a map with (string or list keys) and (string or string) of values. Having variant with duplicate types is allowed but unnecessary and it will complicate things.

You want
std::map<std::string,std::variant<std::string, std::list<std::string>>> i.e. map with string keys and (string or list) values.

This compiles:

#include <iostream>
#include <map>
#include <string>
#include <list>
#include <variant>
// Prefer using in C++ to typedef.
using Dict = std::map<std::string,std::variant<std::string, std::list<std::string>>>;

int main(){
    std::list<std::string> List1 {"Teamwork", "Hate"};
    Dict d;
    d["TIME"] = "8:15";
    d["TAGS"] = List1;

    return 0;
}

Variants are c++17, make sure you have it set if you are getting include errors.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading