Ways to copy a vector in C++ -- c++中复制vector的方法

本文详细介绍了在C++中复制vector的四种方法:迭代法、赋值操作符、“=”运算符、通过构造函数以及使用内置函数。这些方法实现深度复制,确保源vector和目标vector的独立性。文章提供了每种方法的示例代码和输出结果,并推荐了相关主题的文章。
摘要由CSDN通过智能技术生成

 In case of arrays, there is no much choice to copy an array into other, other than iterative method i.e running a loop to copy each element at respective index. But Vector classes has more than one methods to copy entire vector into other in easier ways.There are basically two types of copying :- 在数组方面,复制一个数组到另个里面没有多少方法可以选择,除了循环的方法,比如运行一个循环把每个元素复制到另一个。但是vector有更多的方法。

1 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 new vector.They are deeply copied 这是通常的方法--复制,使用loop。

// C++ code to demonstrate copy of vector 
// by iterative method. 
#include<iostream> 
#include<vector> 
using namespace std; 

int main() 
{ 
	// Initializing vector with values 
	vector<int> vect1{1, 2, 3, 4}; 

	// Declaring new vector 
	vector<int> vect2; 

	// A loop to copy elements of 
	// old vector into new vector 
	// by Iterative method 
	for (int i=0; i<vect1.size(); i++) 
		vect2.push_back(vect1[i]); 

	cout << "Old vector elements are : "; 
	for (int i=0; i<vect1.size(); i++) 
		cout << vect1[i] << " "; 
	cout << endl; 

	cout << "New vector elements are : "; 
	for (int i=0; i<vect2.size(); i++) 
		cout << vect2[i] << " "; 
	cout<< endl; 

	// Changing value of vector to show that a new 
	// copy is created. 
	vect1[0] = 2; 

	cout << "The first element of old vector is :"; 
	cout << vect1[0] << endl; 
	cout << "The first element of new vector is :"; 
	cout << vect2[0] <<endl; 

	return 0; 
} 

Output:

Old vector elements are : 1 2 3 4 
New vector elements are : 1 2 3 4 
The first element of old vector is : 2
The first element of new vector is : 1

In the above code, on changing the value at one vector did not alter value at other vector, hence they are not allocated at same address, hence deep copy. 这种情况下,一个vector的值改变,另一个vector的值不会改变,所以他们分配的地址空间不同,是深度复制。


2 Method 2 : By 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值