Python list equivalent in c++

hi

I'm new to c++, I used python so I have a lot of doubts. My current problem is that I would like to have a list with different variables (like double, string or char), and none of the container objects that I have seen allows to do that (i have check array, vector, deque).

I need that because I have created different classes but all have the same functions names, so i would like to do something like

list[8].function(int arg);

but every element of the list is going to be of a different type. Is there a way to do a list wiht different type elements in c++ ?

any help would appreciated
In your case, you would have to use virtual functions/inheritance to make it work. "Simple" example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//include required crap here

class Base {
public:
    virtual void do_something() = 0;
};

class Derv1 : public Base {
public:
    virtual void do_something() {
        std::cout<<"Derv1 do_something()\n";
    }
};

class Derv2 : public Base {
public:
    virtual void do_something() {
        std::cout<<"Derv2 do_something()\n";
    }
};

int main() {
    std::vector<Base*> my_vec; //make a vector of base pointers
    my_vec.push_back(new Derv1); //since we have a vector of base pointers, we can also store
    //Derv1* and Derv2* in it
    my_vec.push_back(new Derv2);
    my_vec.push_back(new Derv2);

    for(unsigned int i = 0; i < my_vec.size(); ++i) {
        my_vec[i]->do_something(); //call the virtual function
    }

    //EDIT: Forgot to delete the pointers I new'd
    for(unsigned int i = 0; i < my_vec.size(); ++i) {
        delete my_vec[i];
    }

    return 0;
}


The above will print out:
Derv1 do_something()
Derv2 do_something()
Derv2 do_something()
Last edited on
Thanks so much for the detail help firedraco.

I see that it is not as easy as it is in python, but the speed increase worth it.
Topic archived. No new replies allowed.