• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

std::vector inserts a copy or reference of an object?

Lets say I have an object that I dynamically allocated. If I push it into a STL vector, will a reference be inserted into the vector or a copy of this object?

It's a general question. For example:

If I delete v, will object a die as well?

iammilind's user avatar

3 Answers 3

will a reference be inserted into the vector or a copy of this object?

Copy (which means that your class should be copy-able otherwise compiler error).

Clarification : References cannot be assigned in std::vector<> . Also, here object has broader sense, it can be a normal variable or a pointer, but std::vector<> accepts only copy.

Update : Post C++11, most of the standard containers offer std::move() of the object using "rvalue based API methods"; where a copy may not be performed.

SridharKritha's user avatar

If you have an object of type T that you have dynamically allocated and you push a pointer to the object onto a std::vector<T*> , then a copy of the pointer is pushed. If you dereference the pointer and push the result onto a std::vector<T> , then a copy of the object is made. Collections always make copies. So collections of pointers make copies of the pointer and collections of class instances make copies of the instances themselves (using copy construction IIRC).

D.Shawley's user avatar

Have you checked the reference :

Add element at the end

Adds a new element at the end of the vector, after its current last element. The content of this new element is initialized to a copy of x.

This effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call. Reallocations invalidate all previously obtained iterators, references and pointers

Alok Save's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged c++ vector reference copy or ask your own question .

Hot Network Questions

cpp vector insert copy

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Related Articles

Ways to copy a vector in C++

In the case of arrays, there is not much choice to copy an array into another, other than the iterative method i.e running a loop to copy each element at its respective index. But Vector classes have more than one method for copying entire vectors into others in easier ways.

There are basically two types of copying:- 

Method 1: Iterative method. This method is a general method to copy, in this method a loop is used to push_back() the old vector elements into the new vector. They are deeply copied 

In the above code, changing the value at one vector did not alter the value at another vector, hence they are not allocated at the same address, hence deep copy.

Method 2: By assignment “=” operator . Simply assigning the new vector to the old one copies the vector. This way of assignment is not possible in the case of arrays. 

Method 3: By passing vector as constructor. At the time of declaration of vector, passing an old initialized vector copies the elements of the passed vector into the newly declared vector. They are deeply copied. 

Method 4: copy(first_iterator_o, last_iterator_o, back_inserter()) :- This is another way to copy old vector into new one. This function takes 3 arguments, first, the first iterator of the old vector, second, the last iterator of the old vector and third is back_inserter function to insert values from the back. This also generated a deep copy. 

Method 5: assign(first_iterator_o, last_iterator_o): This method assigns the same values to the new vector as the old one. This takes 2 arguments, the first iterator to the old vector and the last iterator to the old vector. This generates a deep copy. 

Method 6: By using insert function. The vector class has a standard function, insert() , that can insert elements from a specified range.

This article is contributed by Manjeet Singh . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

Please Login to comment...

Improve your Coding Skills with Practice

Start your coding journey now.

Containers:

Input/Output:

Multi-threading:

member functions

non-member overloads

std:: vector ::insert

Return value, iterator validity, exception safety.

Data Structure

Ways to copy a vector in C++

There are different ways to copy a vector in C++.

1) std::copy

std:: copy is inbuilt to copy the elements from one vector to another.

Example Code

 Live Demo

2) assign operator

This is also used to copy values from vector 1 to vector 2.

3) By assignment “=” operator

It is a simple way to copy values from vector 1 to vector 2

4) By push_back method

5) by passing vector as constructor.

karthikeya Boyini

I love programming (: That's all I know

0 Followers

Tutorials Point

How to copy an array to an STL vector efficiently?

Consider the following array and std::vector :

Method 1 : Copy the array to the vector using copy and back_inserter

It is probably the easiest to understand. Just copy each element from the array and push it into the back of the vector. Alas, it's slow. Because there's a loop (implied with the copy function), each element must be treated individually; no performance improvements can be made based on the fact that we know the array and vectors are contiguous blocks.

Method 2 : Same as 1 but pre-allocating the vector using reserve

It is a suggested performance improvement to Method 1; just pre-reserve the size of the array before adding it. For large arrays this might help. However the best advice here is never to use reserve unless profiling suggests you may be able to get an improvement (or you need to ensure your iterators are not going to be invalidated). Bjarne agrees. Incidentally, I found that this method performed the slowest most of the time though I'm struggling to comprehensively explain why it was regularly significantly slower than method 1...

Method 3 : Copy the array to the vector using memcpy

It is the old school solution - throw some C at the problem! Works fine and fast for POD types. In this case resize is required to be called since memcpy works outside the bounds of vector and there is no way to tell a vector that its size has changed. Apart from being an ugly solution (byte copying!) remember that this can only be used for POD types. I would never use this solution.

Method 4 : vector::insert

It is the best way to go. Its meaning is clear, it is (usually) the fastest and it works for any objects. There is no downside to using this method for this application.

Method 5: Vector initializer and insert

It is a tweak on Method 4 - copy the array into a vector and then append it. Good option - generally fast and clear.

Method 6: Vector initializer and assignment

It is a tweak on Method 5 - copy the array into a vector and then append it.

Search anything:

Different ways to copy a vector in C++

Software Engineering

Get FREE domain for 1st year and build your brand new site

cpp vector insert copy

Software Engineering C++

Get this book -> Problems on Array: For Interviews and Competitive Programming

Reading time: 30 minutes | Coding time: 5 minutes

An array has a fixed size when it is declared. But if we want a dynamic array whose size can vary at runtime then we use vector. Elements are inserted in vector from end using push_back(). Like arrays, elements in vector are also stored contiguously and they can traversed using iterators. Iterators return pointers to elements.

In this article, we will explore different methods to copy a vector in C++ and all covered methods use deep copy that the memory address of new copy is different from the original vector.

Ways of copying a vector into other

1. iterative method :-.

In this method a loop runs over the old vector and elements are inserted in new vector using push_back().This function inserts elements in vector from back.

Output :- (If inputs are 10,20,30,40)

Old vector elements are : 10 20 30 40 New vector elements are : 10 20 30 40

Complexity :- As the loop traverses all the elements once so complexity is O(n) where n is number of elements in old vector.

2. Assignment operator(=) :-

In this method elements from old vector are inserted into new vector by assigning new vector to old vector. This does not happen in arrays.

Output :- (If inputs are 1,2,3,4) Old vector elements are : 1 2 3 4 New vector elements are : 1 2 3 4

Complexity :- Linear time complexity as elements have to traversed once to assign them to new vector.

3. Passing vector as constructor :-

At the time of declaration of vector, passing old vector as an argument of constructor, copies the elements of passed vector into the newly declared vector.

Output :- Old vector elements are : 1 2 3 4 New vector elements are : 1 2 3 4

Complexity :- O(n) as elements are traversed once when old vector is passed as argument to constructor.

4. Using inbuild functions :-

This function takes 3 arguments, the first iterator of old vector, the last iterator of old vector and third is back_inserter function to insert values from back. We can also pass first iterator + number of elements in place of last iterator and last iterator of new vector in place of back_inserter() if we want to copy a certain portion of elements starting from first element of old vector.

Output :- Old vector elements are : 1 2 3 4 New vector elements of v2 are : 1 2 3 4 New vector elements of v3 are : 1 2 3 0

Complexity :- O(n) as copy() takes linear time to traverse elements. But begin(),end() and back_inserter() takes constant time.

This function takes 2 arguments, first iterator to old vector and last iterator to old vector. It then assigns values of old vector to new vector.

Complexity :- O(n) as assign() takes O(n) time where n is the number of elements in old vector.

Apart from these there are more methods in C++ STL(Standard Template Library) which allows copying of vectors in different manners. They are :-

By using this method we can choose how many elements have to be copied to new vector. It takes 3 arguments :-

iterator_source : The pointer to the beginning of source vector, from where elements have to be started copying. num : Integer specifying how many numbers would be copied to destination vector starting from iterator_source. If a negative number is entered, no operation is performed. iterator_dest : The pointer to the beginning of destination vector, to where elements have to be started copying.

Output :- The new vector elements entered using copy_n() : 1 2 3 4 0 0

Complexity :- Best case of O(1) if no traversal is required. Worst case of O(n) if all elements from old vector are copied to new vector.

copy_if() : This function copies elements according to result of a “condition“ which is provided with the help of a 4th argument, a function returning a boolean value. This function takes 4 arguments, 3 of them similar to copy() and additional function, which when returns true, a number is copied, else number is not copied.

copy_backwards() : This function starts copying elements into the destination vector from backwards and keeps on copying till all numbers are not copied. The copying starts from the “iterator_dest” but in backward direction. It also takes similar arguments as copy().

Output :- The new vector elements entered using copy_if() : 1 3 5 0 0 0 The new vector elements entered using copy_backward() : 0 1 2 3 4 0

Complexity :- Best case of O(1) if no traversal required. Worst case of O(n) as in case of copy() function.

All the ways discussed above implements deep copy which means the location address of old and new vector are different. So, when values of old vector are changed, it does not reflect in new vector.

copy_if() takes how many arguments?

It is same as copy() and one extra argument is for the function returning boolean value according to condition (adsbygoogle = window.adsbygoogle || []).push({}); (adsbygoogle = window.adsbygoogle || []).push({}); riya deb.

Read more posts by this author.

Vote for Riya Deb for Top Writers 2021 :

Improved & Reviewed by:

OpenGenus Foundation

cppreference.com

Std:: copy, std:: copy_if.

Copies the elements in the range, defined by [first, last) , to another range beginning at d_first .

[ edit ] Parameters

[ edit ] return value.

Output iterator to the element in the destination range, one past the last element copied.

[ edit ] Complexity

For the overloads with an ExecutionPolicy, there may be a performance cost if ForwardIt1 's value type is not MoveConstructible .

[ edit ] Exceptions

The overloads with a template parameter named ExecutionPolicy report errors as follows:

[ edit ] Notes

In practice, implementations of std::copy avoid multiple assignments and use bulk copy functions such as std::memmove if the value type is TriviallyCopyable and the iterator types satisfy LegacyContiguousIterator .

When copying overlapping ranges, std::copy is appropriate when copying to the left (beginning of the destination range is outside the source range) while std::copy_backward is appropriate when copying to the right (end of the destination range is outside the source range).

[ edit ] Possible implementation

[ edit ] example.

The following code uses copy to both copy the contents of one vector to another and to display the resulting vector .

Possible output:

[ edit ] See also

Powered by MediaWiki

Copy a vector in C++

This post will discuss how to copy a vector in C++. Copying a vector includes constructing a new vector with a copy of each of the elements in the original vector and in the same order.

1. Using Copy Constructor

The recommended approach is to use the copy constructor, which internally takes care of all copying.

Download    Run Code

  We can also use a range constructor for this:

2. Using vector::operator=

Here, the idea is to create an empty vector and use its member function operator= for copying all elements of the given vector to it.

  We know that an object is passed by value to a function in C++ by default. That means the stack will create the copy of the whole object if the object is passed by value. We can take advantage of this fact and force a copy of the vector, as shown below:

3. Using std::copy function

The standard algorithm for copying is std::copy . We can use it for copying elements from the source vector to the destination vector. But make sure that the destination vector has sufficient space to accommodate all elements of the source sequence.

  If the destination vector doesn’t have enough space for copying, prefer using std::back_insert iterator, which will call vector::push_back on the destination vector, as shown below:

4. Using vector::insert function

The vector class has a standard function, insert() , that can insert elements from a specified range.

5. Using vector::assign function

Here’s another solution using the public member function assign() of the vector class, which replaces the vector contents with contents of the specified range.

6. Using vector::push_back function

Finally, we can call vector::push_back on each of the elements in the given vector using a range-based for-loop. Simple yet efficient.

  Important Note:

Please note that all above solutions perform a shallow copy on the vector object. C++ doesn’t offer any utility function for performing a deep copy. If a deep copy is needed, we can write our own routine, which traverses the vector and manually copy the references to other objects.

That’s all about copying a vector in C++.

Rate this post

Average rating 4.56 /5. Vote count: 9

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

guest

IncludeHelp_logo

IncludeHelp

Home » C++ STL

Different ways to copy a vector in C++

C++ STL | Copying a vector : Learn - different ways to copy a vector in C++ STL, Shallow copy vs Deep copy, Different copy methods, etc. Submitted by Radib Kar , on July 07, 2020

In this article, we are going to see how to copy a vector into another vector in various ways? We will also learn about shallow copy and deep copy , their differences, and consequences while checking each of the vector copy methods.

Before starting with the methods for copying a vector into the other, let's discuss what shallow copy and deep copy are. What are differences b/w them, and why do we need two different terms to classify the copy process.

Shallow copy vs Deep copy

A vector is essentially an object which has some memory allocation upon execution. Now say you have defined and declared some vector A and you want to copy the content of A into another vector B . Now, there can be two cases, one case is we define a new vector B , but doesn't allocate any new memory for that, rather just link up to the vector A similar like vector B is pointing to the same location of vector A . Thus it has the same copy of vector A . This is known as a shallow copy. If we make any changes to vector A even after our copy operation is done, vector B will have the same changes which are not intended.

On the other hand, when we create a new location for vector B and copy contents from vector A , then it's known as deep copy . If we make any change to vector A after the copy operation it won't be reflected in vector B which is of course intended.

While discussing the copy method we will detail whether it's a shallow copy or deep copy and why so that you never make any mistake using the copy method and guess it's a deep copy ! (yes we often intend to have a deep copy normally).

Different copy methods

1) copy content iteratively.

Here we simply copy the contents of vector A into vector B iteratively. Vector B is defined as a new location, so it's of course a deep copy. We have verified that too by changing elements after our copy operation.

Example code:

2) Copy content recursively

Here we simply copy the contents of vector A into vector B recursively. Vector B is defined as a new location, so it's of course a deep copy. We have verified that too by changing elements after our copy operation.

3) Using assignment operator "=" (overwriting the current contents)

Another way to copy a vector into another is by using the assignment operator. Yes, it works perfectly! Don't try this at all for static array!. The reason behind why such assignment operator works because it simply overwrites the current members if any available, else assigns the value from where it's being copied. Below is an example and we can see, it's a deep copy.

Note: In Java, assignment operator does a shallow copy only.

4) Using copy constructor

We can also pass the vector A as a constructor to vector B which will invoke copy constructor and serve a deep copy .

5) std::copy() function

There is another method using the std function copy() . Though it's less used you should know a variety of functions the C++ standard library has. And yes, it does a deep copy. The copy function takes three argument

The first one is: iterator from where copy will be started: beginning of vector A

The second one is: iterator to where copy will be ended: the end of vector A

The third one is: output iterator which points to destination vector: beginning of Vector B

So the syntax is,

A very important note about the above code:

Check here I have defined vector B as vector<int> B(5) , but if you look in earlier codes you will find I had defined like vector<int> B

Now the question is why I made the change this time. Is there any reason or I just did that! Okay, let's say we do the same as before.

Then the code will be:

Oops! The output is segmentation fault! . Why? Probably now you get the point. Whenever we write vector<int> B the vector has no idea about how many elements will be there and it doesn't allocate memory for elements at all. But in our copy function there is the output iterator which tries to traverse vector B, but fails as no memory allocated for elements. That's why segmentation fault and we need to allocate memory, rather say define the vector along with its elements. That's why we need vector<int> B(5) . Go through my article on vector initialization methods to know in details about this. Oops, one little mistake can lead you to segmentation fault and you may just get insane to find the bug! Nice lesson I hope.

6) vector::assign() function

Vector has an inbuilt function too to copy contents from other content. It's named assign() function. It's again a deep copy method.

The syntax is like below,

Okay, that's all. So, we found all the copy methods actually do a good job as they all do deep copy and we can use any one of them blindly. Do comment and let us know which copy method you would prefer and why?

Related Tutorials

Preparation

What's New (MCQs)

Top Interview Coding Problems/Challenges!

Comments and Discussions!

IncludeHelp's Blogs

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML Solved programs: » C » C++ » DS » Java » C# Aptitude que. & ans.: » C » C++ » Java » DBMS Interview que. & ans.: » C » Embedded C » Java » SEO » HR CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS More: » Articles » Puzzles » News/Updates

ABOUT SECTION » About us » Contact us » Feedback » Privacy policy

STUDENT'S SECTION » Internship » Certificates » Content Writers of the Month

SUBSCRIBE » Facebook » LinkedIn » Subscribe through email

© https://www.includehelp.com some rights reserved.

IMAGES

  1. C++ Vector at() function

    cpp vector insert copy

  2. Cpp Vectors graphic art designs in editable .ai .eps .svg format free and easy download unlimit

    cpp vector insert copy

  3. CPP Logo PNG Vector (CDR) Free Download

    cpp vector insert copy

  4. C++, cpp, data format, extension, file format, filetype icon

    cpp vector insert copy

  5. C++ Vector insert() function

    cpp vector insert copy

  6. CPP: Convert Vector to Set

    cpp vector insert copy

VIDEO

  1. Topps Update 2022 JULIO RODRIGUEZ Insert 3 Big Pulls #shorts Relic Foil Cubs Rookie Suzuki

  2. Overpass kill #shorts #volleyballworld #Volleyball #volleyballplayer #Volleyballgame

  3. IVAN & STOKES

  4. copy specific tables and views with data from one database to another on same or different server

  5. Day 3: 14 Days of Valentine’s Day outfits #valentinesday #barbie

  6. insert picture in shape #shape #msword #word #shorts #youtubeshorts #tipsandtricks #mswordtips

COMMENTS

  1. std::vector inserts a copy or reference of an object?

    If you have an object of type T that you have dynamically allocated and you push a pointer to the object onto a std::vector<T*> , then a copy of

  2. Ways to copy a vector in C++

    // copy is created. ... Method 6: By using insert function. The vector class has a standard function, insert(), that can insert elements from a

  3. std::vector::insert

    The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of

  4. Ways to copy a vector in C++

    std::copy(first_iterator_o, last_iterator_o, back_inserter()): first_iteratot_0 = First iterator of first vector. last_iteratot_0 = Last

  5. How to copy an array to an STL vector efficiently? #C++

    dataVec.insert(dataVec.end(), dataArr, dataArr+N);. It is the best way to go. Its meaning is clear

  6. Different ways to copy a vector in C++

    In this method a loop runs over the old vector and elements are inserted in new vector using push_back().This function inserts elements in vector from back.

  7. std::vector<T,Allocator>::insert

    std::vector<T,Allocator>::insert · inserts value before pos. · inserts count copies of the value before pos. · inserts elements from range [first

  8. std::copy, std::copy_if

    When copying overlapping ranges, std::copy is appropriate when copying to the left (beginning of the destination range is outside the source

  9. Copy a vector in C++

    Copy a vector in C++ · 1. Using Copy Constructor · 2. Using vector::operator= · 3. Using std::copy function · 4. Using vector::insert function · 5. Using vector::

  10. Different ways to copy a vector in C++

    Another way to copy a vector into another is by using the assignment operator. Yes, it works perfectly! Don't try this at all for static array!.