c – 为什么“n”在此功能中没有增加?
发布时间:2020-12-16 10:25:10 所属栏目:百科 来源:网络整理
导读:我的代码: #include iostream#include vector#include algorithmint test_n(std::vectorint::iterator b,std::vectorint::iterator e,int n){ n++; std::vectorint::difference_type l = e-b; if (l100) return std::accumulate(b,e,0); std::vectorint::it
我的代码:
#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,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不至少增加一次? 解决方法
n递增.只是C没有在语句中评估参数的固定顺序.因此,在您调用test_n的语句(结尾之前的std :: cout行)中,编译器可能首先决定检查n的值,然后再调用test_n并获取其输出.
我的建议:分开调用 – 在cout之前执行test_n,你应该看到更改. int testnresult = test_n(v.begin(),n); std::cout << testnresult << " (n=" << n << ")n"; 参见例如问题Compilers and argument order of evaluation in C++有关在C中评估参数的顺序的详细信息. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |