How to cast betwen vectors of objects ?

I have two structs and two vectors
1
2
3
4
5
6
7
8
9
10
11
12
struct A {
double A
double B
};

struct B {
A my_A
double C
};

vector<A> vector_of_A
vector<B> vector_of_B


Is there any way to cast these vectors ? ( with some code like this ?)
vector_of_A = (cast_to_A) vector_B ????
vector_of_B = (cast_to_B) vector_A ????



Thanks




Last edited on
You cannot cast directly. But you can cast each entry like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct A {
double A
double B
};

struct B {
A my_A
double C
B(const A &a) : my_A(a) { } // This is needed for implicit conversion!
};

vector<A> vector_of_A
vector<B> vector_of_B
vector_of_B.assign(vector_of_A.begin(), vector_of_A.end()); // Can't use it 
Last edited on
Uhmmm , Thanks !
Wait you can't. 'assign()' takes only iterators. So you must use 'push_back()' for each element

EDIT: Actually my original post was okay!
Last edited on
Your original question doesn't make sense to me: even setting a single 3-d vector to the value of a 2-d vector does not make sense mathematically, as they have different numbers of members.

Can you explain what the purpose of the operation is?

One case where you map 3d vectors onto 2d ones is to work out how to draw a 3d object on a (2d screen). But this process is called projection and involves a transform, not just an equal operator.

(Aside: while it is possible to override operator= to do the required transform, this is a really bad idea as it would break the operator's emantics)
@andywestken
they aren't mathematical vectors.
I always thought "vector" was a misnomer. They really should've named that class something else.
Sorry, by "vector" I was referring to the two classes, not the std::vector.

One of the classes (or rather, structs : A) having 2 doubles, and the other (B) having 3, made me think me about 2D and 3D vectors (in a graphics context).

But that was just an example of when you might make map a triplet into a pair. Unfortunately it led one to use "vector" is an overly confusig manner! :-(

It might help to know what the structs A and B represent?
Last edited on
Topic archived. No new replies allowed.