Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

ellie:)

macrumors newbie
Original poster
Jan 7, 2010
7
0
I am writing a code , to inherit a vector class like this :

struct A {

int dataA;
int dataB;

};

class B : std::vector<A> {

};


May I know, how can assign value to the vector, say dataA =5, data B =6 and the second data A =7, data B =9... and how to access the value when I am running the program? Can I call in this way B[0].dataA ?

thank you..
 
I am writing a code , to inherit a vector class like this :

struct A {

int dataA;
int dataB;

};

class B : std::vector<A> {

};


May I know, how can assign value to the vector, say dataA =5, data B =6 and the second data A =7, data B =9... and how to access the value when I am running the program? Can I call in this way B[0].dataA ?

thank you..

Are you sure you want to _inherit_ from std::vector<A> ? It would be a rare case where this is the right thing to do. Ask yourself about class B: _Is_ it a vector, or does it _contain_ a vector? If it _contains_ a vector then you more likely want

Code:
class B {
    std::vector<A> data;
    ....
};

If class B inherits from std::vector<A> then you use exactly the same methods as for vector<A>. If class B contains a vector, then you would for example access myObject.data which is a vector.

Just realised: Could it be that you don't want to _inherit_ from std::vector at all, that you just want to use a std::vector? You known you can just write

Code:
std::vector <A> myVector;

and myVector will be a vector of struct As. No need for any inheritance at all.
 
Just realised: Could it be that you don't want to _inherit_ from std::vector at all, that you just want to use a std::vector? You known you can just write

Code:
std::vector <A> myVector;

and myVector will be a vector of struct As. No need for any inheritance at all.

This sounds like the most likely case. If B was of type std::vector containing a bunch of struct A's, then std::vector's operator [] could be used as the OP described, then the element returned could be .'d to grab a structure element.

-Lee
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.