×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

Copy a vector to another in C++

C++ vector copy programs: Here, we are going to learn how to copy a vector to another? Here, we are using two different ways to copy one vector to another?
Submitted by IncludeHelp, on September 27, 2018

Steps (ways) to copy a vector to another in C++

The ways that we are using to copy vectors in C++, are:

  1. Copy one vector's elements to another (Simple approach)
  2. Copy vector by using an assignment operator
  3. Copy vector 1 to vector 2 while declaring vector 2 by passing the first vector as an argument (parameterized constructor)

Copy a vector to another in C++ (Using simple approach)

#include <iostream>
#include <vector>
using namespace std;

int main() {
  // declar and initialize vector 1
  vector<int> v1{10, 20, 30, 40, 50};
  // declare vector2
  vector<int> v2;

  // copy v2 to v1
  for (int i = 0; i < v1.size(); i++) {
    v2.push_back(v1[i]);
  }

  // printing v1 and v2
  cout << "v1 elements: ";
  for (int i = 0; i < v1.size(); i++) {
    cout << v1[i] << " ";
  }
  cout << endl;

  cout << "v2 elements: ";
  for (int i = 0; i < v2.size(); i++) {
    cout << v2[i] << " ";
  }
  cout << endl;

  return 0;
}

Output

v1 elements: 10 20 30 40 50
v2 elements: 10 20 30 40 50

Copy a vector to another in C++ (Using assignment operator)

#include <iostream>
#include <vector>
using namespace std;

int main() {
  // declar and initialize vector 1
  vector<int> v1{10, 20, 30, 40, 50};
  // declare vector2
  vector<int> v2;

  // copying v1 to v2
  v2 = v1;

  // printing v1 and v2
  cout << "v1 elements: ";
  for (int i = 0; i < v1.size(); i++) {
    cout << v1[i] << " ";
  }

  cout << endl;
  cout << "v2 elements: ";
  for (int i = 0; i < v2.size(); i++) {
    cout << v2[i] << " ";
  }
  cout << endl;

  return 0;
}

Output

v1 elements: 10 20 30 40 50
v2 elements: 10 20 30 40 50

Copy a vector to another in C++ (while declaring)

Copy vector 1 to vector 2 while declaring vector 2 by passing the first vector as an argument (parameterized constructor).

#include <iostream>
#include <vector>
using namespace std;

int main() {
  // declar and initialize vector 1
  vector<int> v1{10, 20, 30, 40, 50};
  // declare vector2 by copying vector1
  vector<int> v2(v1);

  // printing v1 and v2
  cout << "v1 elements: ";
  for (int i = 0; i < v1.size(); i++) {
    cout << v1[i] << " ";
  }
  cout << endl;
  
  cout << "v2 elements: ";
  for (int i = 0; i < v2.size(); i++) {
    cout << v2[i] << " ";
  }
  cout << endl;

  return 0;
}

Output

v1 elements: 10 20 30 40 50
v2 elements: 10 20 30 40 50

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.