我们如何在C+中实现具有不同数据类型值的映射+;比如PHP?

我们如何在C+中实现具有不同数据类型值的映射+;比如PHP?,php,c++,matrix,data-structures,Php,C++,Matrix,Data Structures,在PHP中,我们可以创建如下数组: $somearray[0]['key1']= $someOtherArray; $somearray[0]['key2']= 6; $somearray[0]['key3']= 12.73647; 这基本上是一个具有不同数据类型值的矩阵($someOtherArray是另一个php数组)。我想用C++实现这个。我应该使用地图还是组合使用两种不同的数据结构或类似的东西?最好的解决方案是什么?多态性如何(只适用于用户定义的类型(因此没有原语)) #包括 #包括

在PHP中,我们可以创建如下数组:

$somearray[0]['key1']= $someOtherArray;
$somearray[0]['key2']= 6;
$somearray[0]['key3']= 12.73647;
这基本上是一个具有不同数据类型值的矩阵(
$someOtherArray
是另一个php数组)。我想用C++实现这个。我应该使用地图还是组合使用两种不同的数据结构或类似的东西?最好的解决方案是什么?

多态性如何(只适用于用户定义的类型(因此没有原语))

#包括
#包括
#包括
类基类{
受保护的:
int x;
公众:
基类(intx):x(x){}
虚拟int GetValue(){return x;}
};
类Child1:公共基类{
公众:
Child1(intx):基类(x){}
int GetValue()重写{return x*2;}
};
int main()
{
地图;
map[0]=std::unique_ptr(新基类(1));
map[1]=std::unique_ptr(new Child1(1));
std::cout GetValue()多态性如何(只适用于用户定义的类型(因此没有原语))

#包括
#包括
#包括
类基类{
受保护的:
int x;
公众:
基类(intx):x(x){}
虚拟int GetValue(){return x;}
};
类Child1:公共基类{
公众:
Child1(intx):基类(x){}
int GetValue()重写{return x*2;}
};
int main()
{
地图;
map[0]=std::unique_ptr(新基类(1));
map[1]=std::unique_ptr(new Child1(1));

std::cout GetValue()听起来你想要
std::variant
std::any
或boost等价物。听起来你想要
std::variant
std::any
或boost等价物。这是std::variant的替代品…对于原语,你可以编写一个包装模板类。对于原语,这是std::variant…的替代品s、 您可以编写一个包装器模板类。
#include <map>
#include <iostream>
#include <memory>

class BaseClass {
protected:
    int x;
public:
    BaseClass(int x) : x(x) {}

    virtual int GetValue() { return x; }
};

class Child1 : public BaseClass {
public:
    Child1(int x) : BaseClass(x) {}
    int GetValue() override { return x * 2; }
};

int main()
{
    std::map<int, std::unique_ptr<BaseClass>> map;

    map[0] = std::unique_ptr<BaseClass>(new BaseClass(1));
    map[1] = std::unique_ptr<BaseClass>(new Child1(1));

    std::cout << map[0]->GetValue() << std::endl;
    std::cout << map[1]->GetValue() << std::endl;

    return 0;
}