如何将计数器变量从一个函数传递到main函数
How can I pass a counter variable from one function to main?
我正在编写一个程序,使用不同的算法对随机数进行排序。我已经创建了bubble_sort函数,并运行了一个测试,以确保它对数字进行了正确排序,但我想检查该函数中进行了多少交换(交换),并将这些数据返回到main。
#include <iostream>
#include <cstdlib>
using namespace std;
const int SIZE = 100;
void random_fill(int numbers[], int size);
int bubble_sort(int numbers[], int size);
int main() {
int arr1[SIZE];
int arr2[SIZE];
random_fill(arr1, SIZE);
//cout << arr1[0] << endl;
//cout << arr1[1] << endl;
// Copy the array contents into arr2
for (int i = 0; i < SIZE; i++)
{
arr2[i] = arr1[i];
}
//cout << arr2[0] << endl;
//cout << arr2[1] << endl;
bubble_sort(arr2, SIZE);
for (int i = 0; i < SIZE; i++)
{
cout << arr2[i] << endl;
}
}
void random_fill(int numbers[], int size)
{
for (int i = 0; i < SIZE; i++)
{
numbers[i] = rand();
}
}
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
int bubble_sort(int list_of_nums[], int size)
{
// We will make a series of passes through the list.
// On each pass through, we look at two numbers at a time.
// If the second number is bigger than the first number,
// swap the first and second number.
// Keep making passes through the list until no more swaps are made.
bool swap_was_made = true; // initialize to true so we can enter the loop
int swaps = 0;
while (swap_was_made)
{
// assume no swaps will happen on this pass
swap_was_made = false;
// Start at the beginning of the list (position 0)
// and start walking forward.
for (int i = 0; i < (size - 1); i++)
{
// Check two numbers at a time (positions 0 and 1),
// then 1 and 2, then 2 and 3, etc...)
if (list_of_nums[i] > list_of_nums[i + 1])
{
// If the first number in position i
// is bigger than the second number in position i + 1.
// And remember that we made a swap!
swap(list_of_nums[i], list_of_nums[i + 1]);
swap_was_made = true;
swaps++;
}
}
}
return swaps;
}
如果你能帮忙,那就太好了。
int bubble_sort(int list_of_nums[], int size)
{
...
return swaps;
}
你为什么有麻烦?您已经使bubble_sort
返回交换计数。
所以,把它储存起来。
int swaps = bubble_sort(arr2, SIZE);
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何仅为一个函数添加延迟
- 构造函数正在调用一个使用当前类类型的函数
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 如何创建函数管道,以便函数一个接一个地运行?
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 在c++中的复制构造函数/一个声明语句中的初始化的延续中使用chain方法
- C :基类调用自己的虚拟函数 - 一个反图案
- 如何在这个交换函数(一个单独的链表)中找到错误
- 两个相同的函数(一个使用模板模式,另一个不使用)
- 你怎么能一次给一个函数一个参数呢
- 为什么要做两个函数?(一个是非const,另一个是const)
- 当代码在其他地方使用时,如何保证函数一个接一个地被调用