简体   繁体   English

如何在 C++ 中映射多个值?

[英]how to map multiple values in c++?

current code当前代码

std::map<std::string,int> m;
...
m.insert(std::pair<std::string,int>(text,lineno));
...
std::cout<<"key: "<<iter->first<<"lineno: "<<iter->second<<std::endl;

how to save mutiple values in same key?如何在同一个键中保存多个值?

std::map<std::string,int> m;

By declaring this (the above) you have instantiated map which the keys of this map (m) of type string and the values are of type int .通过声明 this (the above),您已经实例化了 map,其中string类型的map (m) 的键和值的类型为int

In C++ you can declare a map with keys and values pairs, from any type, what ever you like/need, so the answer would be, vector or depends on what do you want to achieve from this Data Structure .C++你可以声明一个带有键和值对的map ,来自任何类型,你喜欢/需要什么,所以答案是, vector取决于你想从这个Data Structure实现什么。

here is ilustration with vector:这是带有矢量的 ilustration:

std::map<std::string,std::vector<int>> my_map; 

here is ilustration with values of type map:这是带有类型映射值的说明:

std::map<std::string, std::map<std::string, int>> my_map; 

Note笔记

If you are working with c++ version or standard compiler less that c++11 , you need to add space between the adjacent right angle brackets, like so:如果您使用的是c++版本或低于c++11标准编译器,则需要在相邻的右尖括号之间添加空格,如下所示:

std::map<std::string, std::map<std::string, int> > my_map; 

To sum up the comments of others, here's an answer.总结其他人的评论,这里是一个答案。

Say you have some type T and would like to map a std::string to multiple values of that type.假设您有某种类型T并且想要将std::string映射到该类型的多个值。 The easiest way to do this, when you don't know how many multiple values you need to map to, is to use an std::vector <T> .当您不知道需要映射到多少个多个值时,最简单的方法是使用std::vector <T> If you do know how many multiple values you're going to be dealing with for each key, you could map to an std::array <T> .如果您确实知道要为每个键处理多少个多个值,则可以映射到std::array <T>

std::map <std::string, std::vector <int>> map;
map ["A"].push_back(10);
map ["B"].push_back(20);
map ["A"].push_back(42);

You could use a std::multimap <std::string, int> similarly if you're dealing with what I showed above.如果您正在处理我上面显示的内容,您可以类似地使用std::multimap <std::string, int>

std::multimap <std::string, int> map;
map.insert({"A", 10});
map.insert({"B", 20});
map.insert({"A", 42});

If you would like to map one key to multiple values that are to hold information of different types, you could use a std::map <std::string, std::vector <std::tuple <int, std::string, std::pair <int, int>>>> // ...etc.如果您想将一个键映射到多个值以保存不同类型的信息,您可以使用std::map <std::string, std::vector <std::tuple <int, std::string, std::pair <int, int>>>> // ...etc. . .

You could use a vector of some structure data type too as a substitute to tuples in the above example.您也可以使用某种结构数据类型的向量来代替上述示例中的元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM