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

前端 未结 8 1651
一个人的身影
一个人的身影 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条回答
  •  鱼传尺愫
    2020-11-27 17:02

    You can use either structures, or classes or std::pair.

    [edit]

    For classes and structs:

    struct XYZ {
        int x;
        string y;
        double z;
    };
    std::vector container;
    
    XYZ el;
    el.x = 10;
    el.y = "asd";
    el.z = 1.123;
    container.push_back(el);
    

    For std::pair:

    #include 
    typedef std::pair > XYZ;
    std::vector container;
    container.push_back(std::make_pair(10, std::make_pair("asd", 1111.222)));
    

提交回复
热议问题