为什么这个函数中没有对“n”进行递增操作?

3

我的代码:

#include <iostream>
#include <vector>
#include <algorithm>

int test_n(std::vector<int>::iterator b, std::vector<int>::iterator e, int &n)
{
    n++;    
    std::vector<int>::difference_type l = e-b;

    if (l<100) return std::accumulate(b, e, 0);

    std::vector<int>::iterator tmp = b + l/2;
    int nL = test_n(b, tmp, n);
    int nR = test_n(tmp, e, n);

    return nL + nR;
}

int main()
{
    int n=0;
    std::vector<int> v;

    for (int i=1; i<1000; i++) v.push_back(i);
    std::cout << test_n(v.begin(), v.end(), n) << " (n=" << n << ")\n";
    return 0;
}

为什么 n 至少没有被增加一次?

1
你的输出是什么,你期望得到什么? - bkausbk
2
在执行自增操作之前就已经打印了它。输出流参数的求值顺序未指定。尝试在下一行打印 n - juanchopanza
@bkausbk:我正在玩代码片段,这次想要计算递归调用的次数,没有任何理由,只是因为好玩 ;) - slashmais
1个回答

12

n递增了。只是C++在语句中评估参数的顺序没有固定规则。因此,在调用test_n的语句中(就在最后一个std::cout行之前),编译器可能先检查n的值,然后才调用test_n并获取其输出。

我的建议是:将调用分开 - 在输出cout之前执行test_n,您应该会看到变化。所以:

int testnresult = test_n(v.begin(), v.end(), n);
std::cout << testnresult  << " (n=" << n << ")\n";

例如,有关C++中评估参数的顺序的详细信息,请参阅问题Compilers and argument order of evaluation in C++


没错,这就是它 - 应该在某个“陷阱”或“坑”的列表中 :) - slashmais

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接