如何重新分配一个数组到另一个数组?
问题描述:
是否有可能重新分配一个数组到另一个数组?就像这样: 这是功能E02:如何重新分配一个数组到另一个数组?
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;
}
据说这是为了把变量n到数组但阵列仍然需要降。如果我只是这样分配a = b,那么我得到输出15,9,8,4,3,5,其中5是垃圾值。所以我的问题是:有没有办法重新分配一个数组到像这样的不同数组? 如果我使用像
int* &p1;
一个指针,然后把它的功能我得到我想要什么,但功能必须有这些参数,并具有为无效
答
我将提供一些概念,这将可能帮助你得出一个解决您的问题。然后提供一个快速解决方案,可以帮助您解决最终问题。
...如果我只是这样分配a = b,那么我得到输出15,9,8,4,3,5,其中5是垃圾值。
数字5的输出与您在fcn02中赋值a = b无关。值5实际上是调用函数中x的值。您正在访问数组之外的数组,从而访问int大小的下一个地址的值。在这种情况下,它是x的值。如果你吐出x的地址和a [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;
}
使用'的std :: VECTOR' – StoryTeller
我想我说的功能必须是这样。我无法使用矢量 – Oktavix
[我如何在C++中使用数组?](https:// *。com/questions/4810664/how-do-i-use-arrays-in-c) –