Make copy of an array

前端 未结 11 2370
庸人自扰
庸人自扰 2020-11-21 23:05

I have an array a which is constantly being updated. Let\'s say a = [1,2,3,4,5]. I need to make an exact duplicate copy of a and call

11条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 23:29

    I have a feeling that all of these "better ways to copy an array" are not really going to solve your problem.

    You say

    I tried a for loop like [...] but that doesn't seem to be working correctly?

    Looking at that loop, there's no obvious reason for it not to work ... unless:

    • you somehow have the a and b arrays messed up (e.g. a and b refer to the same array), or
    • your application is multi-threaded and different threads are reading and updating the a array simultaneously.

    In either case, alternative ways of doing the copying won't solve the underlying problem.

    The fix for the first scenario is obvious. For the second scenario you will have to figure out some way of synchronizing the threads. Atomic array classes don't help because they have no atomic copy constructors or clone methods, but synchronizing using a primitive mutex will do the trick.

    (There are hints in your question that lead me to think that this is indeed thread related; e.g. your statement that a is constantly changing.)

提交回复
热议问题