简体   繁体   English

从递归返回时字典保持不变

[英]dictionary stays the same when returning from recursion

I have this piece of code that uses recursion to calculate the sum of something on all numbers up to limit. 我有一段代码使用递归来计算所有数字的总和,直到最大。

static long gen(int limit, List<int> primes,int num,int idx,myDict dict,long sum)
    {

        for (int i = idx; i < primes.Count; i++)
        {
            if (num * primes[i] > limit || num * primes[i] < 0)
            {
                return 0;
            }
            dict.update(primes[i]);
            Console.WriteLine("{0}-->{1}", num * primes[i], dict.maxv);
            gen(limit, primes, num * primes[i], i, dict, sum + dict.maxv);
        }
        return sum;
    }

myDict is basically a dictionary that saves it's max value and the key to that value. myDict基本上是一个字典,用于保存其最大值和该值的键。

My problem is that dict is not changing when returning from the recursion. 我的问题是,从递归返回时dict不会改变。 I mean that if for example I debug the function and in the call stack there are a few calls to this function and I try to examine the values of the variables there. 我的意思是,例如,如果我调试该函数并且在调用堆栈中有对该函数的一些调用,那么我将尝试检查那里的变量的值。 num holds the value it should according to when it was called but dict always holds the "newest" value. num保留调用时应根据的值,但是dict始终保留“最新”值。

lets take an example that in the call stack the value for num is currently 8 and dict currently holds the values: 2:(3,4) the dict that we should have is this. 让我们举个例子,在调用堆栈中, num的值当前为8而dict当前包含值: 2:(3,4)我们应该拥有的dict是这个。 but if I examine the previous calls in the call stack I find that in all of them dict has the same value and not the value that it had when the function was could from there. 但是,如果我检查调用堆栈中的先前调用,我会发现dict中的所有dict都具有相同的值,而不是该函数可以从那里获得的值。

I think that maybe there is some conceptual idea that I'm not understanding correctly. 我认为也许有些概念上的想法我没有正确理解。

If myDict is essentially a Dictionary , it is always passed by reference to the gen method. 如果myDict本质上是Dictionary ,则始终通过引用gen方法来传递它。 This means that there is only one instance of myDict and in every iteration of your recursive method dict refers to this one and only instance. 这意味着只有myDict一个实例,并且在递归方法的每次迭代中, dict引用该实例。 Simply returning from gen will pop the reference to your myDict from the stack, but this will not change its contents. 只需从gen返回,就会从堆栈中弹出对myDict的引用,但这不会更改其内容。 If you want to return dict to its previous state, you will have to implement the backtracking yourself. 如果要将dict返回其先前状态,则必须自己实施回溯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM