how to operator a stl vector pointer?

Discussion in 'C++' started by cylin, Dec 23, 2003.

  1. cylin

    cylin Guest

    Dear all,

    Here is my code.
    ------------------------------
    #include <iostream>
    #include <vector>
    using namespace std;

    class A {
    public:
    int a;
    A() { a=0; }
    };

    class B {
    public:
    vector<A*> vecA;
    B() {}
    ~B() {
    for (int i=0;i<vecA.size();i++) {
    if (vecA) {
    delete vecA;
    vecA=NULL;
    }
    }
    vecA.erase(vecA.begin(),vecA.end());
    }
    };

    int main()
    {
    vector<B*>* BB=new vector<B*>;
    // How to get or assign a value of class A object?
    return 0;
    }
    ---------------------------------------

    How to get or assign a value of class A object?
    Thanks for your help.

    Regards,
    cylin.
     
    cylin, Dec 23, 2003
    #1
    1. Advertisements

  2. cylin

    Rolf Magnus Guest

    You should use initializer lists instead:

    A() : a(0) {}

    Doesn't make much of a difference for builtin types, but for classes, it
    does. So it's better to get used to that.


    No need for that erase(). First of all, there is a clear() member
    function, but besides that, a vector is cleared on destruction anyway.
    Why are you using so much pointer stuff? Especially, why are you
    dynamically allocating your vector? This makes things a lot more
    complicated than necessary.
    you mean you want to access an element of a B's vector of A through an
    element of your vector of B's, to which you have a pointer? Sounds way
    too complicated, but here you go:

    (*BB)[3]->vecA[5]->a = 3;


    this will assign 3 to the 'a' member of the fifth element of the 'vecA'
    member of the 3rd element of your B vector through the BB pointer.

    But again, your design is much too complicated, and you don't take real
    advantage of vectors or any OO concepts.
     
    Rolf Magnus, Dec 23, 2003
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.