How can I store objects of differing types in a C++ container?

前端 未结 8 1656
一个人的身影
一个人的身影 2020-11-27 16:26

Is there a C++ container that I could use or build that can contain, say, int and string and double types? The problem I\'m facing is

8条回答
  •  猫巷女王i
    2020-11-27 17:10

    You could use a struct that contains all three.

    struct Data
    {
        int intVal;
        std::string stringVal;
        double doubleVal;
    };
    

    Then you could just declare list mycontainer and use the appropriate value, provided you know what the value type is. If not, add an addition field to the struct that tells you which of the three data types is in use.

    struct Data
    {
        enum DATATYPE { DT_INT, DT_STRING, DT_DOUBLE } type;
    
        int intVal;
        std::string stringVal;
        double doubleVal;
    };
    

    If you're worried about memory usage, you could probably use a union, though I tend to avoid using them. It might be needless paranoia on my part though.

提交回复
热议问题