您的循环完美地工作。该问题必须在代码中的其他位置。
下面是一个例子程序,拷贝三种不同的方式中的数据:一个for
循环,memcpy
和std::copy
:
#include <algorithm>
#include <cstring>
#include <iostream>
#include <iterator>
void copy1(int D[], int A[], int len) {
for(int k = 0; k < len; k++)
D[k] = A[k];
}
void copy2(int D[], int A[], int len) {
std::memcpy(D, A, len*sizeof(int));
}
void copy3(int D[], int A[], int len) {
std::copy(A, A+len, D);
}
int main() {
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *d = new int[10];
std::ostream_iterator<int> out(std::cout, ",");
// First, print the initial values
std::copy(d, d+10, out);
std::cout << "\n";
// Next do the copies and print the values again
copy1(d, a, 10);
std::copy(d, d+10, out);
std::cout << "\n";
copy2(d, a, 10);
std::copy(d, d+10, out);
std::cout << "\n";
copy3(d, a, 10);
std::copy(d, d+10, out);
std::cout << "\n";
}
我得到的输出是:
0,0,0,0,0,0,0,0,0,0,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
请张贴[SSCCE(http://sscce.org/)。 – ildjarn 2012-07-06 23:53:07
如果你可以为你的段落设置可读性的格式,比如突出你的代码,或者把它放在不同的行上,这将会很有帮助。所有穿插在同一字体中的代码都很难做出来。这是为了你自己的利益,你的文章可读性越强,阅读它的人越多,并且希望有所帮助:) – Levon 2012-07-06 23:55:23
有没有理由不能制作'A'和'D''std :: vector's,并且用'D = A;'来复制副本? – 2012-07-07 00:00:59