can I use base class pointer to swap the derived object in a vector?

J

John Black

Hi,
I have 2 vectors, vector<Derived_class*> vec1, vec2; can I do the
following,

for (int i=0; i<vec1.size(); ++i){
for (int j=0; j<vec2.size(); ++j){
if (.. some comparision of vec1 and vec2[j]...){
Base_Class b = vec2;
vec2 = vec2[j];
vec2[j] = b;
}
}
}

Is there any problem here? In swapping I do not cast the pointer.
 
J

John Harrison

Hi,
I have 2 vectors, vector<Derived_class*> vec1, vec2; can I do the
following,

for (int i=0; i<vec1.size(); ++i){
for (int j=0; j<vec2.size(); ++j){
if (.. some comparision of vec1 and vec2[j]...){
Base_Class b = vec2;
vec2 = vec2[j];
vec2[j] = b;
}
}
}

Is there any problem here? In swapping I do not cast the pointer.


You question doesn't make a lot of sense. The code you quote doesn't
compile, so no you can't do that. But why not do it like this?


if (.. some comparision of vec1 and vec2[j]...){
Derived_class* b = vec2;
vec2 = vec2[j];
vec2[j] = b;
}

It seems the obvious thing to do.

john
 
H

Howard

John Black said:
Hi,
I have 2 vectors, vector<Derived_class*> vec1, vec2; can I do the
following,

for (int i=0; i<vec1.size(); ++i){
for (int j=0; j<vec2.size(); ++j){
if (.. some comparision of vec1 and vec2[j]...){
Base_Class b = vec2;


I take it you mean

Base_Class* b = vec2;

?
vec2 = vec2[j];
vec2[j] = b;
}
}
}

Is there any problem here? In swapping I do not cast the pointer.


Assuming that's what you mean, it's fine.

-Howard
 
V

Victor Bazarov

Howard said:
Hi,
I have 2 vectors, vector<Derived_class*> vec1, vec2; can I do the
following,

for (int i=0; i<vec1.size(); ++i){
for (int j=0; j<vec2.size(); ++j){
if (.. some comparision of vec1 and vec2[j]...){
Base_Class b = vec2;



I take it you mean

Base_Class* b = vec2;

?

vec2 = vec2[j];
vec2[j] = b;
}
}
}

Is there any problem here? In swapping I do not cast the pointer.



Assuming that's what you mean, it's fine.


Somehow I think that conversion between Base_Class* (which is what
'b' is) and Derived_class* (which is what 'vec2[j]' is), requires
a cast (a static_cast, for example).

But, I am still not sure why not use 'std::swap'?

std::swap(vec2, vec2[j]);

all type considerations are hidden and taken care of.

Victor
 

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

Forum statistics

Threads
473,772
Messages
2,569,588
Members
45,099
Latest member
AmbrosePri
Top