使用对作为地图中的键(C ++ / STL) [英] Using pair as key in a map (C++ / STL)

查看:188
本文介绍了使用对作为地图中的键(C ++ / STL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从STL中使用一对作为地图的关键。

I want to use a pair from STL as a key of a map.

#include <iostream>
#include <map>

using namespace std;

int main() {

typedef pair<char*, int> Key;
typedef map< Key , char*> Mapa;

Key p1 ("Apple", 45);
Key p2 ("Berry", 20);

Mapa mapa;

mapa.insert(p1, "Manzana");
mapa.insert(p2, "Arandano");

return 0;

}

但是编译器抛出一堆不可读的信息,对C和C ++来说是非常新鲜的。

But the compiler throw a bunch of unreadable information and I'm very new to C and C++.

如何在地图中使用一对键?一般来说,如何使用任何类型的结构(对象,结构体等)作为地图中的关键?

How can I use a pair as a key in a map? And in general How can I use any kind of structure (objects, structs, etc) as a key in a map?

谢谢!

推荐答案

std :: map :: insert 采用单个参数:键值对,所以你需要使用:

std::map::insert takes a single argument: the key-value pair, so you would need to use:

mapa.insert(std::make_pair(p1, "Manzana"));

您应该使用 std :: string 的C字符串。现在,您可能无法获得期望的结果,因为在地图中查找值将通过比较指针而不是比较字符串来完成。

You should use std::string instead of C strings in your types. As it is now, you will likely not get the results you expect because looking up values in the map will be done by comparing pointers, not by comparing strings.

如果您真的想使用C字符串(再次,你不应该),那么你需要使用 const char * 而不是 char * 在您的类型。

If you really want to use C strings (which, again, you shouldn't), then you need to use const char* instead of char* in your types.


总的来说,我如何使用任何类型的结构(对象,结构等)作为地图中的一个关键字

And in general How can I use any kind of structure (objects, structs, etc) as a key in a map?

您需要重载 operator< 键类型或使用自定义比较器。

You need to overload operator< for the key type or use a custom comparator.

这篇关于使用对作为地图中的键(C ++ / STL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆