C++ 如何将数组中的值复制到新数组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20409931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to copy values from an array into a new one?
提问by Peter
I've been trying to figure this out off and on for a week now and I keep running into problems.
一个星期以来,我一直在努力解决这个问题,但我一直遇到问题。
My objective:
我的目标:
Write a function that allocates memory for an integer array. The function takes as an argument an integer pointer, the size of the array, and newSize to be allocated. The function returns a pointer to the allocated buffer. When the function is first called, the size will be zero and a new array will be created. If the function is called when the array size is greater than zero, a new array will be created and the contents of the old array will be copied into the new array. Your instructor has provided arrayBuilder.cpp as starter code for this programming challenge. In addition, Lab9_1.exe is the executable for this application which you can test.
编写一个为整数数组分配内存的函数。该函数将整数指针、数组大小和要分配的 newSize 作为参数。该函数返回一个指向已分配缓冲区的指针。首次调用该函数时,大小将为零,并会创建一个新数组。如果在数组大小大于零时调用该函数,则会创建一个新数组,并将旧数组的内容复制到新数组中。您的讲师提供了 arrayBuilder.cpp 作为此编程挑战的入门代码。此外,Lab9_1.exe 是此应用程序的可执行文件,您可以对其进行测试。
The code:
编码:
#include <iostream>
using namespace std;
int * arrayBuilder(int * arr, int size, int newSize);
void showArray(int * arr, int size);
int main()
{
int * theArray = 0;
int i;
cout << "This program demonstrates an array builder function." << endl << endl;
// create the initial array. The initial size is zero and the requested size is 5.
theArray = arrayBuilder(theArray, 0, 5);
// show the array before values are added
cout << "theArray after first call to builder: " << endl;
showArray(theArray, 5);
// add some values to the array
for(int i = 0; i < 5; i++)
{
theArray[i] = i + 100;
}
// show the array with added values
cout << endl << "Some values stored in the array: " << endl;
showArray(theArray, 5);
// expand the size of the array. size is not the original size. newSize
// must be greater than size.
theArray = arrayBuilder(theArray, 5, 10);
// show the new array with the new size
cout << endl << "The new array: " << endl;
showArray(theArray, 10);
cout << endl;
delete [] theArray; // be sure to do this a1t the end of your program!
system("pause");
return 0;
}
/*
FUNCTION: arrayBuilder
INPUTS Pointer to an array. Size of the array. If size is zero, arr can be NULL.
Size of the new array.
OUTPUTS: Returns a pointer to allocated memory. If newSize is greater than size,
an array of newSize is allocated and the old array is copied into the new
array. Memory pointed to by the old array is deleted. All new elements
are initialized to zero.
*/
int * arrayBuilder(int * arr, int size, int newSize)
{
// TODO: Your code goes here
return NULL; // default return value. No memory allocated!
}
/*
FUNCTION: showArray
INPUTS: Pointer to an array. Size of the array. If size is zero, arr can be NULL.
OUTPUTS: Prints the contents of the array to the console.
*/
void showArray(int * arr, int size)
{
cout << "arr = ";
for(int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
My struggles: I cannot figure out how to switch "arr" and a temporary array's values.
我的挣扎:我不知道如何切换“arr”和临时数组的值。
int * arrayBuilder(int * arr, int size, int newSize)
{
// TODO: Your code goes here
int * temp = new int [newSize];
for (int i = size; i < newSize; i++)
{
*arr = *temp;
temp++;
}
return NULL; // default return value. No memory allocated!
}
another attempt while searching for answers:
寻找答案时的另一种尝试:
int * arrayBuilder(int * arr, int size, int newSize)
{
// TODO: Your code goes here
int * temp = new int [newSize];
memcpy (temp, arr, size *sizeof(int));
// HINT: Design the function before writing it.
delete[] arr;
for (int i = size; i < newSize; i++)
{
temp[i] = i;
}
return NULL; // default return value. No memory allocated!
}
Basically my end goal is to have the answer look like this:
基本上我的最终目标是让答案看起来像这样:
This program demonstrates an array builder function.
theArray after first call to the builder:
arr = 0 0 0 0 0
some values stored in the array:
arr = 100 101 102 103 104
the new array:
arr = 100 101 102 103 104 0 0 0 0 0
PROGRESS!! Its not crashing anymore :-) This is where I'm at now:
进步!!它不再崩溃了 :-) 这就是我现在所处的位置:
This program demonstrates an array builder function.
theArray after first call to builder:
arr = -842150451 0 0 0 0
Some values stored in the array:
arr = 100 101 102 103 104
The new array:
arr = -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -8
42150451 -842150451 -842150451 -842150451
Press any key to continue . . .
I'll keep tinkering and let everyone know if I hit a wall! Thanks again guys!
我会继续修修补补,如果我撞墙了,请让所有人知道!再次感谢各位!
OKAY! finally got it to display properly:
好的!终于让它正确显示:
This program demonstrates an array builder function.
theArray after first call to the builder:
arr = 0 0 0 0 0
some values stored in the array:
arr = 100 101 102 103 104
the new array:
arr = 100 101 102 103 104 0 0 0 0 0
This is what I did. I feel like I may have cheated in the second part when i put 0 values in for "temp". It was my understanding that i was going to take the data from the previous array and put it into the new one, and instead I just remade it. (So it will only work with this particular set of values [only 0's]). Is there a different way I can code the second part so it works universally with whatever values are thrown at it???
这就是我所做的。当我为“temp”设置 0 值时,我觉得我可能在第二部分作弊了。我的理解是,我将从前一个数组中获取数据并将其放入新数组中,而我只是重新制作了它。(所以它只适用于这组特定的值 [只有 0])。有没有一种不同的方法可以编码第二部分,以便它可以普遍适用于抛出的任何值???
int * arrayBuilder(int * arr, int size, int newSize)
{
int i = size;
int * temp = new int [newSize];
// What if the size is 0?
if (size <= 0)
{
while (i < newSize)
{
temp[i] = 0;
i++;
}
}
// Assuming the size _isn't_ 0
else
{
// "a new array will be created" (good)
for (i = 0; i < newSize; i++)
{
// The contents of the "old" array (arr) will be
// copied into the "new" array (temp)
while (i < size)
{
temp[i] = arr[i];
i++;
}
while (i >= size && i < newSize)
{
temp[i] = 0;
i++;
}
// as a hint, you can address the elements in
// both arrays using the [] operator:
// arr[i]
// temp[i]
}
}
// "The function returns a pointer to the allocated buffer."
// So, NULL is wrong, what buffer did you allocate?
return temp; // default return value. No memory allocated!
}
回答by woolstar
You already got the answer here:
你已经在这里得到了答案:
memcpy (temp, arr, size *sizeof(int));
but you are making several other mistakes after that. Primarily, you need to return temp ;
not return NULL ;
但在那之后你又犯了其他几个错误。首先,你需要return temp ;
不return NULL ;
But also you don't need the loop after the delete arr[] ;
但是你也不需要循环之后 delete arr[] ;
Also don't delete arr[]
if size is zero.
delete arr[]
如果大小为零也不要。
回答by Chad
Since you put forth some effort.
既然你付出了一些努力。
Write a function that allocates memory for an integer array.
编写一个为整数数组分配内存的函数。
The prototype for this function was provided for you:
为您提供了此函数的原型:
int * arrayBuilder(int * arr, int size, int newSize);
The function takes as an argument an integer pointer, the size of the array, and newSize to be allocated. The function returns a pointer to the allocated buffer.
该函数将整数指针、数组大小和要分配的 newSize 作为参数。该函数返回一个指向已分配缓冲区的指针。
This says nothing about doing anything with the "old" (passed in) array, so we should assume it needs to be left alone.
这并没有说明对“旧”(传入)数组做任何事情,所以我们应该假设它需要单独留下。
When the function is first called, the size will be zero and a new array will be created.
首次调用该函数时,大小将为零,并会创建一个新数组。
The above text is meaningless given the context. Feel free to tell your instructor I said so. If the size is zero, how do you know how many elements to allocate?
鉴于上下文,上述文本毫无意义。随意告诉你的导师我是这么说的。如果大小为零,你怎么知道要分配多少个元素?
If the function is called when the array size is greater than zero, a new array will be created and the contents of the old array will be copied into the new array.
如果在数组大小大于零时调用该函数,则会创建一个新数组,并将旧数组的内容复制到新数组中。
OK, now the guts of what needs to be done (you're soclose)
好的,现在需要做的事情的勇气(你太接近了)
int * arrayBuilder(int * arr, int size, int newSize)
{
// What if the size is 0?
// Assuming the size _isn't_ 0
// "a new array will be created" (good)
int * temp = new int [newSize];
for (int i = size; i < newSize; i++)
{
// The contents of the "old" array (arr) will be
// copied into the "new" array (temp)
// as a hint, you can address the elements in
// both arrays using the [] operator:
// arr[i]
// temp[i]
// something is wrong here...
*arr = *temp;
// you definitely _don't_ want to do this
temp++;
}
// "The function returns a pointer to the allocated buffer."
// So, NULL is wrong, what buffer did you allocate?
return NULL; // default return value. No memory allocated!
}
回答by Philip
Just to help you realize why the first attempt didn't work:
只是为了帮助您了解为什么第一次尝试不起作用:
*arr = *temp;
This is assigning a value to the old array, from the new array. That's backwards.
这是从新数组中为旧数组赋值。那是倒退。
But it's just targeting the first value, *arr
doesn't change. You increment *temp
, but you also need to increment *arr
. (Also, manual pointer manipulation like that horrifying and memcopy() is a lot better. But hey, this is for learning purposes, right?)
但它只是针对第一个值,*arr
不会改变。你增加*temp
,但你也需要增加*arr
。(另外,像这样的手动指针操作和 memcopy() 要好得多。但是,嘿,这是为了学习目的,对吧?)
Also, think about that loop:
另外,想想那个循环:
for (int i = size; i < newSize; i++)
That's iterating through once for each bit that newSize is bigger than size. But you're doing two things here. 1) Copying over data and 2) initializing the new data. That for loop you have is good for going over the new data, but it's not the loop you want for copying over the data you already have. That would go from zero to size, right?
这是对 newSize 大于 size 的每一位迭代一次。但是你在这里做两件事。1) 复制数据和 2) 初始化新数据。您拥有的 for 循环有利于遍历新数据,但它不是您想要复制已有数据的循环。那将从零到大小,对吧?
And when you're done you need to return the address of the array you built.
完成后,您需要返回您构建的数组的地址。
return NULL; // default return value. No memory allocated!
That's just some dummy mock code. It's a placeholder by the teacher. It's part of the code you're supposed to change.
那只是一些虚拟的模拟代码。这是老师的占位符。这是您应该更改的代码的一部分。
Per your update:
根据您的更新:
I feel like I may have cheated in the second part when i put 0 values in for "temp"
当我为“temp”设置 0 值时,我觉得我可能在第二部分作弊了
Well what else were you going to put in there? You DO copy over the old array data. Then you EXPAND the array. What goes into the new territory? Zero values as a default is perfectly valid.
那么你还打算在那里放什么?您确实复制了旧的数组数据。然后你扩展数组。什么进入新领域?零值作为默认值是完全有效的。
Is there a different way I can code the second part so it works universally with whatever values are thrown at it???
有没有一种不同的方法可以编码第二部分,以便它可以普遍适用于抛出的任何值???
Well yes, but you'd have to actually have something to throw at it. Your ArrayBuilder
function could take in additional arguments, possibly as a variadic function, so it knows what values to put into the new fields. But your function declaration doesn't have that. All it does is make the array bigger.
嗯,是的,但你必须真的有东西可以扔它。你的ArrayBuilder
函数可以接受额外的参数,可能作为一个可变参数函数,所以它知道要放入新字段的值。但是您的函数声明没有那个。它所做的只是使数组更大。
Also, in your last edit you've got those two while loops that iterate through i
inside of a for loop which also iterates through i
. That'll work, but just so you know it's a bit... uncouth. It's the sort of thing that'll get you in trouble when things get more complicated.
此外,在您的最后一次编辑中,您有这两个 while 循环,它们i
在 for 循环内部进行迭代,该循环也通过i
. 那行得通,但只是让您知道这有点……粗俗。当事情变得更复杂时,这种事情会让你陷入困境。
You could do this instead:
你可以这样做:
for (i = 0; i < newSize; i++)
{
if(i < size)
{
temp[i] = arr[i];
}
else // if(i >= size && i < newSize) //Wait a sec, this "if" is superfluous. It's conditions are enforced the the first if and the loop condition.
{
temp[i] = 0;
}
}
You should also probably delete the comments that make it sound like someone else wrote your code for you. Because someone else did your homework for you. It's best to
您可能还应该删除那些听起来像是其他人为您编写代码的注释。因为别人为你做了功课。最好是
Finally, THOU SHALT INDENT THY CODE!
最后,你应该缩进你的代码!
回答by Vlad from Moscow
If I have correctly understood the assignment the function should look the following way. First of all I would substitute the function declaration
如果我正确理解了赋值,函数应该如下所示。首先我会替换函数声明
int * arrayBuilder(int * arr, int size, int newSize);
for
为了
int * arrayBuilder( const int *arr, size_t size, size_t newSize );
Here is its definition
这是它的定义
int * arrayBuilder( int * arr, int size, int newSize)
{
int *tmp = 0;
if ( newSize >= 0 )
{
tmp = new int[newSize] {};
int copy_size = std::min( size, newSize );
if ( copy_size > 0 ) std::copy( arr, arr + copy_size, tmp );
}
delete []arr;
return tmp;
}
回答by Mr_Tanki_Online_Pro_TO
Try this:
尝试这个:
Code:
代码:
#include <iostream>
using namespace std;
int a[3] =
{
1,
2,
3
};
int b[3];
int main ()
{
cout << endl;
cout << "Array #1 elements: " << endl;
for(int i = 0; i < 3; ++i)
{
cout << a[i] << " ";
}
for(int i = 0; i < 3; ++i)
{
b[i] = a[i];
}
cout << endl << endl;
cout << "Copying Array #1 elements to Array #2..." << endl;
cout << endl;
cout << "Array #2 elements: " << endl;
for(int i = 0; i < 3; ++i)
{
cout << b[i] << " ";
}
cout << endl << endl;
return 0;
}
回答by Konrad Rudolph
This is horribly complex code. Programming is all about reducingcomplexity.
这是极其复杂的代码。编程就是降低复杂性。
With that in mind, here's a proper C++ solution:
考虑到这一点,这里有一个合适的 C++ 解决方案:
std::vector<int> arr = {1, 2, 3, 4, 5};
std::vector<int> copy = arr;
That's it. I hope this exemplifies why you shoulduse the standard library (or other appropriate libraries) rather than re-inventing the wheel. From the code you've posted I am assuming that you've learned (or are learning) C++ from a horrible book or course. Trash that and get a proper book. C++ is complex enough as it is, no need to add needless complexity.
就是这样。我希望这能说明为什么您应该使用标准库(或其他适当的库)而不是重新发明轮子。从您发布的代码中,我假设您已经从一本糟糕的书或课程中学习(或正在学习)C++。把它扔掉,找一本合适的书。C++ 已经足够复杂了,不需要增加不必要的复杂性。