温馨提示×

C++ Map容器能否存储自定义类型

c++
小樊
101
2024-07-21 02:56:56
栏目: 云计算

是的,C++的Map容器可以存储自定义类型。要在Map容器中存储自定义类型,需要定义一个比较函数或者重载<运算符,以便Map容器可以正确比较和排序自定义类型的对象。例如:

#include <iostream>
#include <map>

class MyType {
public:
    int value;
    
    MyType(int val) : value(val) {}
    
    bool operator<(const MyType& other) const {
        return value < other.value;
    }
};

int main() {
    std::map<MyType, int> myMap;
    
    myMap[MyType(1)] = 10;
    myMap[MyType(2)] = 20;
    
    for (auto& pair : myMap) {
        std::cout << "Key: " << pair.first.value << ", Value: " << pair.second << std::endl;
    }
    
    return 0;
}

在上面的例子中,我们定义了一个名为MyType的自定义类型,并在Map容器中存储了这个自定义类型的对象作为键,以及与之关联的整数值作为值。我们重载了<运算符,以便Map容器可以正确比较MyType对象。

0