在地图 C++ 中使用 List

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8192570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:09:06  来源:igfitidea点击:

Use of List inside map C++

c++

提问by user987316

Can I use following syntax:

我可以使用以下语法吗:

 std::map<int,std::list<int>> mAllData;

Where Key Value(int) will be ID of data, and said data could have multiple types so storing all them against said key value. I am trying to use it.

其中 Key Value(int) 将是数据的 ID,并且所述数据可以有多种类型,因此将所有这些类型存储在所述键值上。我正在尝试使用它。

回答by bames53

std::map<int,std::list<int>> my_map;
my_map[10].push_back(10000);
my_map[10].push_back(20000);
my_map[10].push_back(40000);

Your compiler may not support the two closing angle brackets being right next to each other yet, so you might need std::map<int,std::list<int> > my_map.

您的编译器可能尚不支持将两个右尖括号紧挨着,因此您可能需要std::map<int,std::list<int> > my_map.

With C++11 my_mapcan be initialized more efficiently:

使用 C++11my_map可以更有效地初始化:

std::map<int,std::list<int>> my_map {{10, {10000,20000,40000}}};

Also, if you just want a way to store multiple values per key, you can use std::multimap.

此外,如果您只是想要一种为每个键存储多个值的方法,您可以使用 std::multimap。

std::multimap<int,int> my_map;
my_map.insert(std::make_pair(10,10000));
my_map.insert(std::make_pair(10,20000));

And in C++11 this can be written:

在 C++11 中,这可以写成:

std::multimap<int,int> my_map {{10,10000},{10,20000}};