how to operator a stl vector pointer?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • cylin

    how to operator a stl vector pointer?

    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[i]) {
    delete vecA[i];
    vecA[i]=NULL;
    }
    }
    vecA.erase(vecA .begin(),vecA.e nd());
    }
    };

    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.



  • Rolf Magnus

    #2
    Re: how to operator a stl vector pointer?

    cylin wrote:
    [color=blue]
    > Dear all,
    >
    > Here is my code.
    > ------------------------------
    > #include <iostream>
    > #include <vector>
    > using namespace std;
    >
    > class A {
    > public:
    > int a;
    > A() { a=0; }[/color]

    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.
    [color=blue]
    > };
    >
    > class B {
    > public:
    > vector<A*> vecA;
    > B() {}
    > ~B() {
    > for (int i=0;i<vecA.size ();i++) {
    > if (vecA[i]) {
    > delete vecA[i];
    > vecA[i]=NULL;
    > }
    > }
    > vecA.erase(vecA .begin(),vecA.e nd());[/color]

    No need for that erase(). First of all, there is a clear() member
    function, but besides that, a vector is cleared on destruction anyway.
    [color=blue]
    > }
    > };
    >
    > int main()
    > {
    > vector<B*>* BB=new vector<B*>;[/color]

    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.
    [color=blue]
    > // How to get or assign a value of class A object?[/color]

    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.
    [color=blue]
    > return 0;
    > }
    > ---------------------------------------
    >
    > How to get or assign a value of class A object?
    > Thanks for your help.
    >
    > Regards,
    > cylin.[/color]

    Comment

    Working...