By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,217 Members | 1,677 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,217 IT Pros & Developers. It's quick & easy.

how to operator a stl vector pointer?

P: n/a
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.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.

Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
cylin wrote:
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[i]) {
delete vecA[i];
vecA[i]=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.
return 0;
}
---------------------------------------

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

Regards,
cylin.


Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.