c++ - 在映射中使用对作为键 (C++/STL)

标签 c++ stl map std-pair

我想使用 STL 中的一对作为映射的键。

#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++ 很陌生。

如何在 map 中使用一对作为键?一般来说,我如何使用任何类型的结构(对象、结构等)作为映射中的键?

谢谢!

最佳答案

std::map::insert接受一个参数:键值对,所以你需要使用:

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

您应该使用 std::string而不是您的类型中的 C 字符串。就像现在一样,您可能不会得到您期望的结果,因为在映射中查找值将通过比较指针而不是通过比较字符串来完成。

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

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

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

关于c++ - 在映射中使用对作为键 (C++/STL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3277172/

相关文章:

c++ - #define 字符串的类型是什么?

c++ - 从围绕 xyz 的旋转找到 xyz 方向

c++ - 子缓冲区实现

android - C++11 cmath 函数不在带有 gcc-4.8 或 clang 3.4 的 android NDK 的 std 命名空间中

c++ - SWIG Python 到 C++ : TypeError trying to set struct member of type map<string, int>

java - 如何正确使用同步链接 HashMap

c++ - STL std::map 的 MFC 等价物

c++ - 在某个类的析构函数中删除指向对象的指针会自动从堆中删除吗?

c++ - 在 QJsonArray 中搜索项目

c++ - vector 的 STL vector - 好主意吗?调整 "inner" vector 大小的机制?