我想使用 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/