badboy11
badboy11

Reputation: 541

C++ Equivalent of C# Arraylist to hold Multiple Data Types

Looking for an equivalent container class that matches to C#'s Arraylist collections class. Is there anything that comes close to a container that can provide index based enumeration as well as hold multiple data types.

What I am trying to do is implement a Model-View-Controler. I am trying to create a Controller that can internally manage different types of shape data-types (e.g.: Box2D, Circle2D, Circle3D, etc)

//Controller code
class Controller
{
    //internally track all shapes...

    void CreateShape(const Box2d &box); 
    void CreateShape(const Box3d &box);
    void CreateShape(const Circle2d &circle);

    //More Add/Edit/Remove Shape methods...

    void Reset(); //clear the container of shapes...
};

I am trying to create an vector or a different type of container that can hold multiple data types. For example:

//Is this line of code possible??
vector <int, string> vec;    

int i=0;
string str = "test";

//add different data-type objs into my vector mutable array
vec.push_back(i);
vec.push_back(str);

Please advise, if there are other container classes in C++ that might help me achieve this functionality or there is a way to use vector class to store multiple data-types.

Upvotes: 2

Views: 1413

Answers (2)

Collin
Collin

Reputation: 12287

You may want something like this:

class Shape {
public:
    virtual void rotate(double degrees) = 0;
    virtual void scale(double newScale) = 0;
    virtual ~Shape(){}
    //etc, etc, etc...
};

class Box2d : public Shape {
public:
    virtual void rotate(double degrees) {
        //Code for rotating...
    }

    //Implement other virtual methods...
};
class Circle2d : public Shape {}; //Implement virtual methods
class Box3d : public Shape {}; //Implement virtual methods


int main() {
    vector<Shape*> items;
    items.push_back(new Box2d());
    items.push_back(new Circle2d());

    //Now doing this:
    items[i]->rotate(180.0);
    //Will call Box2d's rotate function
}

Upvotes: 3

L7ColWinters
L7ColWinters

Reputation: 1362

The only way your going to put more than one data type into a vector is to encapsulate it.

Upvotes: 0

Related Questions