如何使C++递归程序终止
How to make the C++ recursion program terminate
为什么程序在返回后没有终止,如何让它终止?https://ideone.com/9Lz6jy注意:这里的目的是找到中位数,如果这有助于理解程序。但我的问题纯粹C++相关。无需帮助查找中位数。请专注于我一旦找到答案,我该如何返回答案。
#include <iostream>
#include <time.h>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <assert.h>
using namespace std;
int Pivot2(vector<int> &v, int pivot) {
vector<int> v_copy(v.size());
//int pivot = v.size() / 2;
//1. Sort the array about the mid term
int count_less = 0;
int j = 0;
for (unsigned int i = 0; i <v.size() ; i++) {
if (v[i]< v[pivot]) {
v_copy[j]=v[i];
j++;
count_less++;
}
}
v_copy[j]=v[pivot];
j++;
for (unsigned int i = 0; i <v.size(); i++) {
if (v[i]> v[pivot]) {
v_copy[j] = v[i];
j++;
}
}
//2. if the number of less than than tmp_med increase the middle postion
if ( count_less > v.size() / 2) {
Pivot2(v_copy,count_less-1);
}
else if (count_less == v.size() / 2) {
cout <<"inner " << v[pivot] <<endl ;
return v[pivot]; //Why the recursion does not terminate with this return?
}
else {
if ( count_less < v.size() / 2) {
Pivot2(v_copy, count_less + 1 );
}
}
}
int main() {
// your code goes here
int arr[] = { 8, 7, 3, 1, 9, 4, 6, 5, 2};
int n = sizeof(arr) / sizeof(arr[0]);
//randomize(arr, n);
vector<int> v( begin(arr), end(arr) );
int med1 = Pivot2(v,v.size()/2);
assert(5 == med1);
cout << med1 <<endl ;
return 0;
}
您需要从此块返回所有条件下的值:
if ( count_less > v.size() / 2) {
return Pivot2(v_copy,count_less-1);
}
else if (count_less == v.size() / 2) {
cout <<"inner " << v[pivot] <<endl ;
return v[pivot]; //Why the recursion does not terminate with this return?
}
else {
if ( count_less < v.size() / 2) {
return Pivot2(v_copy, count_less + 1 );
}
}
首先,在有符号和无符号整数表达式之间进行多次比较时启用编译器警告。 即:if ( count_less > v.size() / 2) {
然后,您需要返回您创建Pivots
return Pivot2(v_copy,count_less - 1);
^^^^^^^^
.....
return Pivot2(v_copy, count_less + 1 );
^^^^^^
另外,请注意您的函数reaches end of non-void function
。只需删除if ( count_less < v.size() / 2) {
即可。即:
else {
return Pivot2(v_copy, count_less + 1 );
}
您可以在Coliru上查看此版本
相关文章:
- 声明一个变量,该变量在 c++ 或 c 中具有值,当程序终止时不会被销毁
- 程序终止时调用函数
- 当主终端关闭时,程序终止
- 程序终止,状态为 -1073741510 在 for 循环的中间,将输入分配给二维数组
- 条件运算符不允许程序终止
- 尝试对对象数组进行排序时程序终止
- 程序终止索引外部
- 程序终止,而不是继续整数输入验证循环
- 程序终止时堆栈损坏?
- 如何使用unique_ptr声明调用构造函数并处理程序终止信号
- 使用 ASSERT_DEATH 时,有没有办法在应用程序终止后自动继续执行所有测试
- C++输入超过 11 个整数时程序终止
- 程序终止:使用向量集的向量
- 我该如何验证给定类的每个实例都被应用程序终止所破坏
- 程序终止时,仪器不会捕获未删除对象
- C程序终止
- 正确关闭应用程序:终止程序的替代方案
- 程序终止C++时访问冲突
- 我需要循环这个,并在给出字符串 -1 时让程序终止
- 绑定错误 98 "Address in use"应用程序终止后仍然存在