How to store more than 2 variables in an unordered_map?

大憨熊 提交于 2019-12-11 03:22:35

问题


How can I store more than 2 variables in an std::unordered_map?

I want something like this:

std::unordered_map<string, int, int, int> mapss = {{"a",1,1,1},{"b",1,2,3}};

回答1:


If the string is the key, and the rest are values, then you could have the value be a tuple.

unordered_map<string, tuple<int, int, int>> mapss

Of if you don't know how many values will be there, you can use a vector

unordered_map<string, vector<int>> mapss



回答2:


You can use an std::tuple, as Cyber mentioned, but I suggest creating a simple struct if you know what the values represent.

It expresses your intent clearly.

Example:

struct Color
{
    int r, g, b;
};

std::unordered_map<std::string, Color> colors = 
{
    {"red",  {255, 0, 0}},
    {"blue", {0, 0, 255}}
};


来源:https://stackoverflow.com/questions/28796290/how-to-store-more-than-2-variables-in-an-unordered-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!