BOOL 在给定代码中的作用是什么?
What is the role of BOOL in the given code?
这是一个使用模板函数对各种类型的数据进行排序的c++代码。有人可以详细说明 BOOL 在这里做什么吗?
我读过 bool 数据类型。它基本上只假定两个值 TRUE 和 FAlSE。但是我不知道 BOOL 在这里的作用是什么?
using namespace std;
#include <iostream>
template <class T>
void sort (T array[], int size)
{ int j;
T temp;
int pass;
static int call = 0;
bool xchange = true;
for (pass = 1; pass < size && xchange == true; pass++)
{ xchange = false;
for (j=0; j < size - pass; j++)
{ if (array[j] > array[j+1])
{ temp = array[j]; array[j] = array[j+1]; array[j+1] = temp;
xchange = true;
} /* end of if */
} /* end of inner for loop */
};
call ++;
cout << " within sort : value of call is " << call << endl;
/* end of outer for loop */
} /* end of bubble sort */
int main() {
int a[] = {1,5,6,4,0,8,5,7,9,2};
int a1[] = {1,5,6,4,0,8,5,7,9,2};
char b[] = { 'a', 'c', 'f', 'd', 'b' };
sort (a, 10);
for ( int i=0; i < 10; i++ ) cout << a[i] << " ";
cout << endl;
sort (b, 5);
for ( int i=0; i < 5; i++ ) cout << b[i] << " ";
cout << endl;
sort (a1, 10);
for ( int i=0; i < 10; i++ ) cout << a1[i] << " ";
cout << endl;
return 0;
}
示例中的 bool 用于检查 for 循环的该迭代中是否发生了任何交换。如果没有交换发生 == 数组已排序,则排序算法完成。
给这个函数一个已经排序的数组将显示布尔值的用途。在整个数组的第一次迭代中,不会发生任何交换(因为数组已经排序)-> xchange 从未设置为 true -> 排序算法完成 == for 循环条件中的条件为 false .
它是为了不做你不必做的工作。
这是一个使用模板函数对各种类型的数据进行排序的c++代码。有人可以详细说明 BOOL 在这里做什么吗? 我读过 bool 数据类型。它基本上只假定两个值 TRUE 和 FAlSE。但是我不知道 BOOL 在这里的作用是什么?
using namespace std;
#include <iostream>
template <class T>
void sort (T array[], int size)
{ int j;
T temp;
int pass;
static int call = 0;
bool xchange = true;
for (pass = 1; pass < size && xchange == true; pass++)
{ xchange = false;
for (j=0; j < size - pass; j++)
{ if (array[j] > array[j+1])
{ temp = array[j]; array[j] = array[j+1]; array[j+1] = temp;
xchange = true;
} /* end of if */
} /* end of inner for loop */
};
call ++;
cout << " within sort : value of call is " << call << endl;
/* end of outer for loop */
} /* end of bubble sort */
int main() {
int a[] = {1,5,6,4,0,8,5,7,9,2};
int a1[] = {1,5,6,4,0,8,5,7,9,2};
char b[] = { 'a', 'c', 'f', 'd', 'b' };
sort (a, 10);
for ( int i=0; i < 10; i++ ) cout << a[i] << " ";
cout << endl;
sort (b, 5);
for ( int i=0; i < 5; i++ ) cout << b[i] << " ";
cout << endl;
sort (a1, 10);
for ( int i=0; i < 10; i++ ) cout << a1[i] << " ";
cout << endl;
return 0;
}
示例中的 bool 用于检查 for 循环的该迭代中是否发生了任何交换。如果没有交换发生 == 数组已排序,则排序算法完成。 给这个函数一个已经排序的数组将显示布尔值的用途。在整个数组的第一次迭代中,不会发生任何交换(因为数组已经排序)-> xchange 从未设置为 true -> 排序算法完成 == for 循环条件中的条件为 false . 它是为了不做你不必做的工作。