I'm working off of someone's code. There is a vector of struct P
(Segment
). I want to have different types of P
. Therefore I defined struct P2 : P
. But, since Segment
takes just P
and not P*
, I cannot add element of type P2
to the Segment
and use dynamic_cast
since it will create a new element of type P and copy just i
and I lose the name
information.
What are my options here? Do I just have to change vector<P>
to vector<P*>
and adjust the code everywhere it's being used or create my own type Segment vector<P*>
and use where I need it?
Also, why it was used vector<P>
and not vector<P*>
from the beginning since the vector can have hundreds and even thousands of elements?
struct P
{
int i;
P(int i2) : i(i2) {}
}
struct P2 : P
{
string name;
P2(string name2, int i) : P(i), name(name2) {}
}
struct P3 : P
{
...
}
using Segment = vector<P>;
` you can also go with `std::vector` as @user7860670 suggested since it ensures type safety and you don't have to deal with pointers, _"Also, why it was used in the first place"_...hard to say without more context
– underloaded_operator May 24 '23 at 20:06` and not `vector
` from the beginning since the vector can have hundreds and even thousands of elements?* `vector` is at its best when it can contain objects rather than pointers. It reduces overhead from pointer-chasing and improves cache friendliness because all of the data is in a nice, straight line.
– user4581301 May 24 '23 at 20:09` would be better than `vector
`. It brings extra problems and no obvious gains. Why do you think it might be preferable?
– john May 24 '23 at 20:31` was chosen *from the beginning*. Your situation now is different and `vector
` is one solution. Some others are described in the answer below.
– john May 25 '23 at 05:51