void e02(){
int a[] = {15, 9, 8, 4, 3};
int n = 5;
int x = 5;
fn02(a, n, x);
cout << endl;
for(int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
这是函数fn02:
void fn02(int* a, int &n, int x){
n += 1;
int* b = new int[n];
int j = 0;
bool put = false;
for(int i = 0; i < n; i++){
if(x > a[i] && put == false){
b[j] = x;
j++;
a--;
put = true;
} else{
b[j] = a[i];
j++;
} //else
} //i loop
a = b;
}
nis应该将变量n放入数组中,但数组仍然需要下降。如果我只是这样分配了A = B,那么我将获得输出15、9、8、4、3、5,其中5个为垃圾值。所以我的问题是:有没有办法将数组重新分配到此处的其他数组? 如果我使用的指针喜欢
int* &p1;
我将提供一些概念,这些概念有可能帮助您为问题提供解决方案。 然后提供一个快速解决方案,可以帮助您解决最终解决方案。
数字5的输出与您在FCN02中的A = B的分配无关。 值5实际上是调用函数中x的值。 您正在访问其原始分配边界之外的数组,从而访问INT大小的下一个地址的值。 在这种情况下,它是x的值。 如果您吐出X的地址和[6]的地址,您会发现它们是平等的。 a = b的FCN02中的分配是由于将值传递给函数的基本概念而无法正常工作。 当您调用函数fcn02(a)时,值“ a”(数组开头的地址)被复制为fcn02中的“ a”值。 更改FCN02中的“ A”不会更改呼叫函数中的A”。 示例澄清
注(使用相同的值“ a”可能会令人困惑,所以我对其进行了一些更改)。int func02( int* b ) // address of a is copied to b
{
... // some code...c is dynamically allocated and has an address of 0x80004d30
b = c; // b is set to address of c; thus, b address is now 0x80004d30
// a is unchanged and you now have a memory leak since you didn't delete b.
}
int main()
{
int a[5] = {1,2,3,4}; // address is 0x28cc58
func02(a); // complier will make a copy of the value of a to b
// address (i.e. value) of a is still 0x28cc58
}
为何看到5:
int a[5] = {1,2,3,4,5}; // 0x28cc64
int x = 7; // 0x28cc5c
{ array a }{ x }
---- ---- ---- ---- ---- ----
| 1 | 2 | 3 | 4 | 5 | 7 |
---- ---- ---- ---- ---- ----
如何回答您的问题,您不能将一个数组分配给另一个数组。
int a[5] = {1,2,3,4,5};
int b[5];
b = a;
for ( int i = 0; i<5; ++i )
{
cout << b[i] << endl;
}
编译器将不允许这样做。 这里是快速而肮脏的解决方案,以使您的功能参数相同以进行指导:
void e02(){
int a[6] = {15, 9, 8, 4, 3, 0};
int sizeofA = 5;
int numToAdd = 5;
fn02(a, sizeofA, numToAdd);
cout << endl;
for(int i = 0; i < n; i++) {
cout << a[i] << " ";
}
}
void fn02(int* a, int &n, int x) {
n += 1;
int i = 0;
while( i < n ) {
if ( a[i] > x ) {
++i;
}
else {
int tmp = a[i];
a[i] = x;
x = tmp;
}
}
}
在顺序将元素插入到分类的向量(减少顺序)中,您可以尝试以下操作:
#include <iostream>
#include <vector>
using namespace std;
void InsertItemInSortedArray(std::vector<int>& vec, int item)
{
auto high_pos=std::lower_bound (vec.rbegin(), vec.rend(), item);
vec.insert(high_pos.base(), item);
}
int main() {
std::vector<int> vec = {15, 9, 8, 4, 3};
int item = 5;
InsertItemInSortedArray(vec, item);
for (const auto& elem : vec)
{
std::cout << elem << std::endl;
}
return 0;
}