在 C++ 中搜索并插入具有 3 个元素的映射;

发布于 2024-08-24 06:22:49 字数 127 浏览 3 评论 0原文

我需要有一个像这样的地图:

typedef std::map<int, float , char> Maptype ;

在此地图中插入和搜索对元素的语法是什么。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

几味少女 2024-08-31 06:22:49

map 只能将一种键类型映射到一种数据类型。如果数据包含 2 个元素,请使用结构体或 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;

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.

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;
少女七分熟 2024-08-31 06:22:49

你不能拥有三个元素。 STL map 存储一个键值对。您需要决定要使用什么作为密钥。完成后,您可以将其他两个嵌套在单独的映射中并将其用作:

typedef std::map<int, std::map<float, char> > MapType;

为了插入映射,请使用 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 ...
}

此外,您还可以查看 Boost.Tuple

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:

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.

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.

所谓喜欢 2024-08-31 06:22:49

使用其中一个

std::map<std::pair<int, float>, char>

std::map<int, std::pair<float, char> >

哪个是正确的。

Use either

std::map<std::pair<int, float>, char>

or

std::map<int, std::pair<float, char> >

whichever is correct.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文