问题描述
我正在将一个向量复制到另一个相同类型的向量.并且修改了复制向量但原始向量也在更新我不明白为什么?
i am copying a vector to another vector of same type.and modifying the copy vector but the original vector is also getting update i don't understand why?
vectorfinished_copy=new vector (); finished_copy=finished;
我在修改前后打印原始向量的值
i am printing the value of original vector after and before modification
for(int k=0;k和打印原件但两者不同
请帮帮我
推荐答案
你没有做任何拷贝.您所做的只是将相同的 vector 分配给另一个变量:
you're not doing any copy. all you're doing is assigning the same vector to another variable:
之前:
finished ------> [a, b, c, d]之后:
finished ------> [a, b, c, d] ^ | finished_copy ---/以下是将 vector 的所有元素复制到另一个 vector 中的方法:
here's how you would copy all the elements of a vector into another one:
vectorfinishedcopy = new vector<>(finished); 或
vectorfinishedcopy = new vector<>(); finishedcopy.addall(finished); 然而,这将创建两个不同的向量,其中包含对相同分配实例的引用.如果您想要的是这些对象的副本,那么您需要创建显式副本.如果不进行复制,更改第一个列表中对象的状态也会更改其在第二个列表中的状态,因为两个列表都包含对相同对象的引用.
this, however, will create two different vectors containing references to the same allocated instances. if what you want is a copy of those objects, then you need to create explicit copies. without doing a copy, changing the state of an object in the first list will also change its state in the second one, since both lists contain references to the same ojects.
注意:
- 类应以大写字母开头
- 变量不应包含下划线,而应为驼峰式
- 向量不应再使用.arraylist 应该是,因为 java 2.我们在 java 8.
上善若水38677209