- 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?
- 1 Please show the code you are thinking of :-) – Martin Kristiansen Dec 17, 2011 at 14:18
- 4 The preachy side of me is coming out and I feel I must tell you that you very likely do not mean the STL but rather the C++ standard library. – Corbin Dec 17, 2011 at 14:20
- 1 The C++ standard library has adopted the STL for it's containers and algorithms. So, technically, a STL vector is the same as a C++ library vector. – Emile Cormier Dec 17, 2011 at 14:23
- 1 possible duplicate of When adding an element to a vector, how to know that a copy of the object is going to be made? – Cody Gray ♦ Dec 17, 2011 at 14:23
- 3 Man, I used to care about the difference between the STL and the C++ standard library, but then I joined Stack Overflow and my stack started overflowing with nitpicky comments about the difference, and I suddenly just stopped caring altogether. Unless the difference is relevant to your question (and it's not here), I don't understand how it possibly matters. – Cody Gray ♦ Dec 17, 2011 at 14:28
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.

- I was surprised, I thought the compiler would optimize away the copy operation in some cases, but found it didn't: ideone.com/b4fpc even with g++ -O6 – matiu Dec 17, 2011 at 14:40
- This one demonstrates how expensive the copy operation can be by copying a 131 KB object: ideone.com/UNKyr – matiu Dec 17, 2011 at 14:58
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).
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

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 .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- What's the difference between a power rail and a signal line?
- Is there a single-word adjective for "having exceptionally strong moral principles"?
- Tips for golfing in SVG
- A-Z related to countries
- Why do many companies reject expired SSL certificates as bugs in bug bounties?
- Is a PhD visitor considered as a visiting scholar?
- Is it correct to use "the" before "materials used in making buildings are"?
- Why is there a voltage on my HDMI and coaxial cables?
- Theoretically Correct vs Practical Notation
- Recovering from a blunder I made while emailing a professor
- How to always have spaces around \circ?
- Finite abelian groups with fewer automorphisms than a subgroup
- What is the correct way to screw wall and ceiling drywalls?
- Does a summoned creature play immediately after being summoned by a ready action?
- Movie with vikings/warriors fighting an alien that looks like a wolf with tentacles
- Is there any way to orbit around the object instead of a 3D cursor?
- Wahoo Kickr with 8 speed cassette?
- "We, who've been connected by blood to Prussia's throne and people since Düppel"
- Resistance against timing attacks of AES candidates
- Largest Binary Area
- Calculating probabilities from d6 dice pool (Degenesis rules for botches and triggers)
- ncdu: What's going on with this second size column?
- Stored Procedure Tuning Help
- Equations in two lines
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 .
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Android App Development with Kotlin(Live)
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- React JS (Basic to Advanced)
- JavaScript Foundation
- Complete Data Science Program(Live)
- Mastering Data Analytics
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
Ways to copy a vector in C++
- Initialize a vector in C++ (7 different ways)
- fill in C++ STL
- fill() and fill_n() functions in C++ STL
- What are the default values of static variables in C?
- Understanding “volatile” qualifier in C | Set 2 (Examples)
- Const Qualifier in C
- Initialization of static variables in C
- Understanding “register” keyword in C
- Understanding “extern” keyword in C
- Storage Classes in C
- Static Variables in C
- Memory Layout of C Programs
- How to deallocate memory without using free() in C?
- Difference Between malloc() and calloc() with Examples
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- How to dynamically allocate a 2D array in C?
- How to pass a 2D array as a parameter in C?
- Multidimensional Arrays in C / C++
- 2D Vector In C++ With User Defined Size
- Vector of Vectors in C++ STL with Examples
- Vector in C++ STL
- The C++ Standard Template Library (STL)
- Sort in C++ Standard Template Library (STL)
- Arrays in C/C++
- std::sort() in C++ STL
- Bitwise Operators in C/C++
- Core Dump (Segmentation fault) in C/C++
- Difficulty Level : Easy
- Last Updated : 16 Feb, 2023
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...
- susobhanakhuli
- cpp-algorithm-library
- cpp-strings-library
Improve your Coding Skills with Practice
Start your coding journey now.
- <cassert> (assert.h)
- <cctype> (ctype.h)
- <cerrno> (errno.h)
- C++11 <cfenv> (fenv.h)
- <cfloat> (float.h)
- C++11 <cinttypes> (inttypes.h)
- <ciso646> (iso646.h)
- <climits> (limits.h)
- <clocale> (locale.h)
- <cmath> (math.h)
- <csetjmp> (setjmp.h)
- <csignal> (signal.h)
- <cstdarg> (stdarg.h)
- C++11 <cstdbool> (stdbool.h)
- <cstddef> (stddef.h)
- C++11 <cstdint> (stdint.h)
- <cstdio> (stdio.h)
- <cstdlib> (stdlib.h)
- <cstring> (string.h)
- C++11 <ctgmath> (tgmath.h)
- <ctime> (time.h)
- C++11 <cuchar> (uchar.h)
- <cwchar> (wchar.h)
- <cwctype> (wctype.h)
Containers:
- C++11 <array>
- <deque>
- C++11 <forward_list>
- <list>
- <map>
- <queue>
- <set>
- <stack>
- C++11 <unordered_map>
- C++11 <unordered_set>
- <vector>
Input/Output:
- <fstream>
- <iomanip>
- <ios>
- <iosfwd>
- <iostream>
- <istream>
- <ostream>
- <sstream>
- <streambuf>
Multi-threading:
- C++11 <atomic>
- C++11 <condition_variable>
- C++11 <future>
- C++11 <mutex>
- C++11 <thread>
- <algorithm>
- <bitset>
- C++11 <chrono>
- C++11 <codecvt>
- <complex>
- <exception>
- <functional>
- C++11 <initializer_list>
- <iterator>
- <limits>
- <locale>
- <memory>
- <new>
- <numeric>
- C++11 <random>
- C++11 <ratio>
- C++11 <regex>
- <stdexcept>
- <string>
- C++11 <system_error>
- C++11 <tuple>
- C++11 <type_traits>
- C++11 <typeindex>
- <typeinfo>
- <utility>
- <valarray>
- vector<bool>
- vector::~vector
- vector::vector
member functions
- vector::assign
- vector::back
- vector::begin
- vector::capacity
- C++11 vector::cbegin
- C++11 vector::cend
- vector::clear
- C++11 vector::crbegin
- C++11 vector::crend
- C++11 vector::data
- C++11 vector::emplace
- C++11 vector::emplace_back
- vector::empty
- vector::end
- vector::erase
- vector::front
- vector::get_allocator
- vector::insert
- vector::max_size
- vector::operator[]
- vector::operator=
- vector::pop_back
- vector::push_back
- vector::rbegin
- vector::rend
- vector::reserve
- vector::resize
- C++11 vector::shrink_to_fit
- vector::size
- vector::swap
non-member overloads
- relational operators (vector)
- swap (vector)
std:: vector ::insert
Return value, iterator validity, exception safety.
- Coding Ground
- Corporate Training
- Trending Categories

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
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.

I love programming (: That's all I know
0 Followers
- Related Articles
- Python - Ways to Copy Dictionary
- How to copy elements of ArrayList to Java Vector
- How to append a vector in a vector in C++?
- How to initialize a vector in C++?
- Passing a vector to constructor in C++
- How to implement a copy constructors in C++?
- Sorting a vector in C++
- How to shuffle a std::vector in C++
- How to copy files into a directory in C#?
- Different ways to start a Task in C#
- Different methods to copy in C++ STL - std::copy(), copy_n(), copy_if(), copy_backwards()
- vector::resize() vs vector::reserve() in C++
- Check if it is possible to reach vector B by rotating vector A and adding vector C to its in Python
- How to reverse a Vector using STL in C++?
- C++ Program to Convert Vector to a List

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

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 :-
- copy(first_iterator, last_iterator, back_inserter()) :-
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.
- assign(first_iterator, last_iterator) :-
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 :-
- copy_n(iterator_source, num, iterator_dest) :
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:

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:
- If execution of a function invoked as part of the algorithm throws an exception and ExecutionPolicy is one of the standard policies , std::terminate is called. For any other ExecutionPolicy , the behavior is implementation-defined.
- If the algorithm fails to allocate memory, std::bad_alloc is thrown.
[ 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
- Recent changes
- Offline version
- What links here
- Related changes
- Upload file
- Special pages
- Printable version
- Permanent link
- Page information
- In other languages
- This page was last modified on 3 February 2023, at 14:49.
- This page has been accessed 1,556,276 times.
- Privacy policy
- About cppreference.com
- Disclaimers

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?

- Data Structure
- Coding problems
- Kotlin programs
- C Interview programs
- C++ Aptitude
- Java Aptitude
- C# Aptitude
- PHP Aptitude
- Linux Aptitude
- DBMS Aptitude
- Networking Aptitude
- AI Aptitude
- MIS Executive
- HR Interview Que.
- Web Technologie MCQs
- CS Subjects MCQs
- Databases MCQs
- Programming MCQs
- Testing Software MCQs
- Commerce MCQs
- More MCQs...
- CS fundamental
- Operating systems
- Computer networks
- Software Engineering
- Discrete Mathematics
- Digital Electronics
- Data Mining
- Embedded systems
- Cloud computing
- Cryptography
- Big Data & Hadoop
- Machine Learning
- More Tutorials...
- Tech Articles
- Code Examples
- Programmer's Calculator
- XML Sitemap Generator

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
- Create and initialize a vector using different ways in C++ STL
- Access vector elements using for each loop in C++ STL
- Different ways to access elements from a Vector in C++ STL
- vector::size() function with example in C++ STL
- vector::max_size() function with example in C++ STL
- vector::resize() function with example in C++ STL
- vector::capacity() function with example in C++ STL
- vector::empty() function with example in C++ STL
- vector::reserve() function with example in C++ STL
- vector::shrink_to_fit() function with example in C++ STL
- vector::swap() function with Example in C++ STL
- Push and print elements in an integer vector in C++ STL
- Push and print elements in a float vector in C++ STL
- Check vector is empty or not | C++ STL
- Copy a vector to another in C++
- Copy a vector to another by using vector.assign() function in C++
- Erase elements in C++ Vector using vector::erase()
- Find largest and smallest elements in a vector | C++ STL
- Insert elements in vector using vector::insert() | C++ STL
- C++ STL sort function to sort an array or vector
- Appending a vector to a vector in C++ STL
- Difference between size and capacity of a vector in C++ STL
- Minimum and maximum elements of a vector in C++ STL
- How to find the maximum/largest element of a vector in C++ STL?
- How to find the minimum/smallest element of a vector in C++ STL?
- How to reverse vector elements in C++ STL?
- How to find the sum of elements of a vector in C++ STL?
- How to join two vectors in C++ STL?
- How to find common elements between two Vectors using in C++ STL?
- How to copy array elements to a vector in C++ STL?
- Changing a particular element of a vector in C++ STL
- 2D vector in C++ STL with user defined size
- How to check whether an element exists in a vector in C++ STL?
Preparation
What's New (MCQs)
- C Language MCQs
- Python MCQs
- MongoDB MCQs
- Blockchain MCQs
- AutoCAD MCQs
- ASP.Net MCQs
- JavaScript MCQs
- jQuery MCQs
- ReactJS MCQs
- AngularJS MCQs
- Advanced CSS MCQs
- PL/SQL MCQs
- Oracle MCQs
- SQLite MCQs
- CouchDB MCQs
- MariaDB MCQs
- MS Word MCQs
- MS Excel MCQs
- MS PowerPoint MCQs
- Google Sheets MCQs
- Software Engineering MCQs
- Operating System MCQs
- Data Analytics and Visualization MCQs
- WordPress MCQs
- Blogging MCQs
- Digital Marketing MCQs
- Online Marketing MCQs
- Adobe After Effects MCQs
- Adobe Dreamweaver MCQs
- Adobe Illustrator MCQs
- CorelDRAW MCQs
- Google Chrome MCQs
- Bugzilla MCQs
- OpenStack MCQs
- JMeter MCQs
- ETL Testing MCQs
- Appium MCQs
- Control Systems MCQs
- PySpark MCQs
- Cucumber Testing MCQs
- UiPath MCQs
- TestNG MCQs
- Software Architecture MCQs
- Software Testing MCQs
- Selenium MCQs
- Agile Methodology MCQs
- AWS (Amazon Web Services) MCQs
- Microsoft Azure MCQs
- Energy & Environment Engineering MCQs
- Project Management MCQs
- Marketing MCQs
- Generally Accepted Accounting Principles MCQs
- Bills of Exchange MCQs
- Business Environment MCQs
- Sustainable Development MCQs
- Marginal Costing and Absorption Costing MCQs
- Globalisation MCQs
- Indian Economy MCQs
- Retained Earnings MCQs
- Depreciation MCQs
- Partnership MCQs
- Sole Proprietorship MCQs
- Goods and Services Tax (GST) MCQs
- Cooperative Society MCQs
- Capital Market MCQs
- Business Studies MCQs
- Basic Accounting MCQs
- MIS Executive Interview Questions
- Go Language Interview Questions
Top Interview Coding Problems/Challenges!
- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path
Comments and Discussions!
IncludeHelp's Blogs
- Do's and Don'ts For Dressing Up For Interviews
- Tips To Improve Spoken English
- 20 Smart Questions To Ask During An Interview
- Common Body Language Mistakes to Avoid During Interviews
- Is it important to have a college degree in today's world?
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
VIDEO
COMMENTS
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
// copy is created. ... Method 6: By using insert function. The vector class has a standard function, insert(), that can insert elements from a
The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of
std::copy(first_iterator_o, last_iterator_o, back_inserter()): first_iteratot_0 = First iterator of first vector. last_iteratot_0 = Last
dataVec.insert(dataVec.end(), dataArr, dataArr+N);. It is the best way to go. Its meaning is clear
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.
std::vector<T,Allocator>::insert · inserts value before pos. · inserts count copies of the value before pos. · inserts elements from range [first
When copying overlapping ranges, std::copy is appropriate when copying to the left (beginning of the destination range is outside the source
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::
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!.