数组在 C++ 中不使用 static in 函数时不会修改
array not modifying without using static in function in c++
因为数组名称就像指向数组起始地址的指针,所以当传递给函数时,为什么数组没有修改。当我使用静态指针只存储数组的地址时。之后,使用数组名称返回数组不会引起任何问题。为什么会这样?
#include<iostream>
using namespace std;
int main()
{
int a[10]={2,16,19,20,2,9,18};
int* bubble(int [],int);
cout<<"the sorted array is ";
int n=10;
int *ma=bubble(a,n);
for(int i=0;i<10;i++)
{
cout<<ma[i]<<'n';
}
return 0;
}
int* bubble(int *a,int n)
{
int no_of_comparisons;
int ptr,temp;
static int *ma=a;
while(no_of_comparisons<=n-1-1)
{
ptr=0;
while(ptr<=n-1-no_of_comparisons-1)
{
if(a[ptr]>a[ptr+1])
{
temp=a[ptr];
a[ptr]=a[ptr+1];
a[ptr+1]=temp;
}
ptr+=1;
}
no_of_comparisons+=1;
}
return a;
}
顺便说一下,气泡排序是最简单的算法,也是非常大的输入中最慢的算法。基本思想是,只是遍历从 i=0 到 n 的数组,如果相邻元素顺序不正常,则交换相邻元素。下面我重写了您的代码,使其更具可读性、清晰和简短。我希望它有帮助。
#include<iostream>
int* bubble(int [], int);
int main()
{
int arr[10] = {2, 16, 19, 20, 28, 9, 18, 22, 32,1};
int arr_size = 10;
std::cout << "Original Array: n";
for(int i = 0; i < 10; i++)
std::cout << arr[ i ]<< 'n';
bubble(arr, arr_size);
std::cout << "Sorted Array: n";
for(int i = 0; i < 10; i++)
std::cout << arr[ i ]<< 'n';
return 0;
}
int* bubble(int *a, int n)
{
for(int i = 0; i < n; i++)
{
for(int j = n - 1; j > i; j--)
{
if( a[j] < a[j - 1] )
{
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
return a;
}
代码中的主要问题是,首先没有初始化no_of_comparisons变量。在你的情况下,我认为应该是0
。
相关文章:
- 创建具有 new in 函数和"this is nullptr"异常的对象
- std::complex<> in C++ 数学特殊函数:技术规范或提案
- 类中的数组变量C++导致"was not declared in this scope"实现文件的一个函数中错误,但在构造函数中不会导致错误
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 为什么我们需要 & in 绑定成员函数?
- 数组在 C++ 中不使用 static in 函数时不会修改
- 在使用 In Order 遍历成员函数时引发异常(堆栈溢出)时出现问题
- 使用多重性函数与 in C++ 联合两个链表
- c++:在函数返回过程中,"catching reference in value"与"catching value in value"有什么区别?
- 为什么C++ std::min_element 库函数接受采用布尔返回类型的函数对象的函子,而不是像 C 中那样的 in
- 传递自定义函数类型时的'incompatible types in assignment'
- 是否有内置函数返回" the number of true value in a boolean vector "?
- 如何从类调用函数 - 错误"was not in the scope"
- 使用 static int 返回 int&in 函数
- 在函数调用中使用类型vector<pair<int,int>>::iterator&in
- main.cpp中的错误:函数库中的函数"not declared in this scope",但实际上是
- 尝试在 eclipse CDT 中提取函数时"Too many declarations in selection"错误消息
- 为什么sleep in函数忽略了程序中的几个顺序指令
- 从C++调用 lua 函数时"Error in error handling"
- 运行 WinForm 的函数"In Background" (VS2010 c++)