how to operator a stl vector pointer?

C

cylin

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.
 
R

Rolf Magnus

cylin said:
Dear all,

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

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

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.
};

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());


No need for that erase(). First of all, there is a clear() member
function, but besides that, a vector is cleared on destruction anyway.
}
};

int main()
{
vector<B*>* BB=new vector<B*>;

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

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.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top