阅读量:100
是的,C++的Map容器可以存储自定义类型。要在Map容器中存储自定义类型,需要定义一个比较函数或者重载<运算符,以便Map容器可以正确比较和排序自定义类型的对象。例如:
#include
#include
class MyType {
public:
int value;
MyType(int val) : value(val) {}
bool operator<(const MyType& other) const {
return value < other class="hljs-function">int main() {
std::mapint> myMap;
myMap[MyType(1)] = 10;
myMap[MyType(2)] = 20;
for (auto& pair : myMap) {
std::cout << "Key: " << pair class="hljs-string">", Value: " << pair class="hljs-keyword">return 0;
}
在上面的例子中,我们定义了一个名为MyType的自定义类型,并在Map容器中存储了这个自定义类型的对象作为键,以及与之关联的整数值作为值。我们重载了<运算符,以便Map容器可以正确比较MyType对象。