Copy or clone a collection in Julia

后端 未结 2 1671
余生分开走
余生分开走 2020-12-30 04:21

I have created a one-dimensional array(vector) in Julia, namely, a=[1, 2, 3, 4, 5]. Then I want to create a new vector b, where b has

2条回答
  •  执念已碎
    2020-12-30 04:28

    You can use the copy and deepcopy functions:

    help?> copy
    search: copy copy! copysign deepcopy unsafe_copy! cospi complex Complex complex64 complex32 complex128 complement
    
      copy(x)
    
      Create a shallow copy of x: the outer structure is copied, but not all internal values. For example, copying an
      array produces a new array with identically-same elements as the original.
    
    help?> deepcopy
    search: deepcopy
    
      deepcopy(x)
    
      Create a deep copy of x: everything is copied recursively, resulting in a fully independent object. For example,
      deep-copying an array produces a new array whose elements are deep copies of the original elements. Calling deepcopy
      on an object should generally have the same effect as serializing and then deserializing it.
    
      As a special case, functions can only be actually deep-copied if they are anonymous, otherwise they are just copied.
      The difference is only relevant in the case of closures, i.e. functions which may contain hidden internal
      references.
    
      While it isn't normally necessary, user-defined types can override the default deepcopy behavior by defining a
      specialized version of the function deepcopy_internal(x::T, dict::ObjectIdDict) (which shouldn't otherwise be used),
      where T is the type to be specialized for, and dict keeps track of objects copied so far within the recursion.
      Within the definition, deepcopy_internal should be used in place of deepcopy, and the dict variable should be
      updated as appropriate before returning.
    

    Like this:

    julia> a = Any[1, 2, 3, [4, 5, 6]]
    4-element Array{Any,1}:
     1       
     2       
     3       
      [4,5,6]
    
    julia> b = copy(a); c = deepcopy(a);
    
    julia> a[4][1] = 42;
    
    julia> b    # copied
    4-element Array{Any,1}:
     1
     2
     3
      [42,5,6]
    
    julia> c    # deep copied
    4-element Array{Any,1}:
     1
     2
     3
      [4,5,6]
    

    Notice that the help system hints of the existence of other copy related functions.

提交回复
热议问题