Reputation: 557
!Hi I have a hard time trying to copy vector of pointers to Point. I have a
vector<Point*> oldVector
and I want to copy this vector into other vector. So I used a copying constructor. I did this that way
vector<Point*> newVector = vector<Point*>(oldVector.begin(),oldVector.end());
Unfortunately I get an exception/error if I ran this function.
vector interators incompatible
What may be the problem ??
EDIT There must be a bigger problem with iterators, it seems that I can't use iterators at all. I wanted to add two stl vectors into each other so I used wrote sth like this
vector<int> a, b;
b.insert(b.end(), a.begin(), a.end());
and I get the sama exception/error during execution of this line
Upvotes: 5
Views: 16713
Reputation: 58725
Because the original container is of identical type, std::vector<Point*>
, there's no need to use the range constructor; simply use the copy constructor!
std::vector<Point*> newVector(oldVector);
But that's not the main concern here. The main issue here is that of shared pointers. Be very clear with yourself who owns the pointed-at data. Be careful of double-delete!
Upvotes: 1
Reputation: 14791
That would be either
vector<Point*> *newVector = new vector<Point*>(oldVector.begin(),oldVector.end());
or
vector<Point*> newVector(oldVector.begin(),oldVector.end());
When creating objects, you only use assignment when allocating from the heap. Otherwise, you simply place the constructor argument(s) inside parentheses after your new variable name.
Alternatively, the following is much simpler:
vector<Point*> newVector(oldVector);
Upvotes: 18
Reputation: 76795
That should work (just tested with std::vector<int>
s). There must be some other problem. Does Point
have a copy constructor?
Upvotes: 0
Reputation: 361792
vector<Point*> newVector = vector<Point*>(oldVector.begin(),oldVector.end());
Why this?
Why not this:
vector<Point*> newVector(oldVector.begin(),oldVector.end());
??. The latter the better!
Even better is this,
vector<Point*> newVector(oldVector);
Upvotes: 1
Reputation: 814
You want
Vector<Point*> newVector(oldVector.begin(), oldVector.end());
Upvotes: 0