在 C++ 中使用 3 个元素在地图中搜索和插入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2392093/
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
Searching and Inserting in a map with 3 elements in C++
提问by John
I need to have a map like this :
我需要有这样的地图:
typedef std::map<int, float , char> Maptype ;
What is the syntax to insert and searching elements of pair in this map.
在此映射中插入和搜索 pair 元素的语法是什么。
回答by kennytm
A map
can only map one key type to one data type. If the data contains 2 elements, use a struct or a std::pair
.
Amap
只能将一种键类型映射到一种数据类型。如果数据包含 2 个元素,请使用 struct 或std::pair
.
typedef std::map<int, std::pair<float, char> > Maptype;
...
Maptype m;
m[123] = std::make_pair(0.5f, 'c');
...
std::pair<float, char> val = m[245];
std::cout << "float: " << val.first << ", char: " << val.second << std::endl;
回答by dirkgently
You cannot have three elements. The STL map
stores a key-value pair. You need to decide on what you are going to use as a key. Once done, you can probably nest the other two in a separate map and use it as:
你不能拥有三个元素。STLmap
存储一个键值对。您需要决定将什么用作密钥。完成后,您可能可以将其他两个嵌套在单独的地图中并将其用作:
typedef std::map<int, std::map<float, char> > MapType;
In order to insert in a map, use the operator[]
or the insert
member function. You can search for using the find
member function.
为了在地图中插入,请使用operator[]
或insert
成员函数。您可以使用find
成员函数进行搜索。
MapType m;
// insert
m.insert(std::make_pair(4, std::make_pair(3.2, 'a')));
m[ -4 ] = make_pair(2.4, 'z');
// fnd
MapType::iterator i = m.find(-4);
if (i != m.end()) { // item exists ...
}
Additionally you can look at Boost.Tuple.
此外,您可以查看Boost.Tuple。
回答by avakar
Use either
使用任一
std::map<std::pair<int, float>, char>
or
或者
std::map<int, std::pair<float, char> >
whichever is correct.
哪个是正确的。