Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Heterogeneous Containers

http://gethelp.dev-archive.com/techtips/cpp_pro/10min/10min0900.asp

Danny,
extending from your article above, suppose I have the following two vectors
class A{
int ID;
string name;
}
vector<A> x
vector<B> y //where B inherits from A.

I already have x and y populated by x.push_back(A(...)) and y.push_back(B(...)).

Now if I want to combine these into a single vector, I'll need to create a new
vector<A*> z and use:

z.push_back( new A(...));
z.push_back( new B(...));

so the best way to populate z would be using a copy constructor?
such as z.push_back(new A(a[i]));

So what about when it comes time to do sorting? since z is type A*, sort will sort according to memory address rather than ID?

at runtime, how do you determine the real class that each variable is pointing to? a bunch of if statements testing for the correct class?

Thanks!
[989 byte] By [rssmps] at [2007-11-11 8:08:55]
# 1 Re: Heterogeneous Containers
As expected, when I did a sort, it was by memory rather than by value.
00FCFF78 10
01015F78 602
0174FF38 20016
03633BB8 30
03656F78 80
04177258 40
04375160 400
0438A250 300
04610658 29130
06AC1FF0 60

so I thought of the following:

bool operator<( const TypeCORD2C* itemA, const TypeCORD2C* itemB){
if(itemA->CID<itemB->CID)
return true;
else
return false;
};

However, it gave me this error:

error C2803: 'operator <' must have at least one formal parameter of class type

is sort not available for a general container??
rssmps at 2007-11-11 21:01:35 >
# 2 Re: Heterogeneous Containers
Byu default, sort will sort raw pointers. You need to use a third argument for sort. This is called a comparitor. It's a function object that implements the < operator. This function object knows that the two arguments are pointers to A, so it returns :

if(itemA->CID < itemB->CID)
return true;
return false;

Notice also that modern C++ apps use advanced techniques for implementing heterogeneous containers such as shared_ptr http://www.dev-archive.com/cplus/10MinuteSolution/28347,
or the Boost.Any library
http://www.dev-archive.com/cplus/10MinuteSolution/29757

In a properly design application, you never really need to know whether the pointer elements in the vector are pointers to A or B. You simply call their member functions, which are supposed to ve virtual, and C++ does the right thing anyway. If you really have to recover the actual type, you can use RTTI.
Danny at 2007-11-11 21:02:40 >