Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL cloning a vector

Tags:

c++

stl

vector

!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

enter image description here

like image 258
Berial Avatar asked Feb 24 '11 19:02

Berial


People also ask

Can you memcpy into a vector?

You can use the Use memcpy for vector assignment parameter to optimize generated code for vector assignments by replacing for loops with memcpy function calls. The memcpy function is more efficient than for -loop controlled element assignment for large data sets. This optimization improves execution speed.

How are vectors implemented in STL?

Vector is implemented as a dynamically allocated array. The memory for this array is allocated in the constructor. As more elements are inserted the array is dynamically increased in size. A constructor without parameter creates an array with a default size.


2 Answers

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);
like image 153
Mac Avatar answered Oct 06 '22 00:10

Mac


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);
like image 39
Nawaz Avatar answered Oct 06 '22 01:10

Nawaz