C++ 在没有循环的情况下设置一个数组等于另一个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13054243/
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
Set one array equal to another without a loop
提问by nan
In C++ say we have two arrays:
在 C++ 中,我们有两个数组:
a[5] = {1,2,3,4,5};
b[5] = {5,4,3,2,1};
If we wanted to set, for instance, a equal to b, how can we achieve that without using a loop?
例如,如果我们想设置 a 等于 b,我们如何在不使用循环的情况下实现这一点?
My thought is to use recursion, but I'm not exactly sure how.
我的想法是使用递归,但我不确定如何使用。
Edit: Sorry, should have made it clear I don't want to use the standard library functions (including memcpy which some of you have mentioned)
编辑:对不起,应该说清楚我不想使用标准库函数(包括你们中的一些人提到的 memcpy)
回答by egrunin
int a[5] = {1,2,3,4,5};
int b[5] = {5,4,3,2,1};
memcpy(a, b, sizeof(a));
回答by R. Martinho Fernandes
You can use the copy algorithm from the standard library.
您可以使用标准库中的复制算法。
std::copy(std::begin(b), std::end(b), std::begin(a));
std::begin
and std::end
are new in the C++ standard library, but they're easy to implement for compilers that don't support them yet:
std::begin
并且std::end
是 C++ 标准库中的新内容,但对于尚不支持它们的编译器,它们很容易实现:
template <typename T, std::size_t N>
T* begin(T(&a)[N]) {
return &a[0];
}
template <typename T, std::size_t N>
T* end(T(&a)[N]) {
return begin(a) + N;
}
Alternatively, you can use std::array
(or the equivalent from Boost for older compilers) and the assignment operator:
或者,您可以使用std::array
(或用于较旧编译器的 Boost 中的等效项)和赋值运算符:
std::array<int, 5> a = {1,2,3,4,5};
std::array<int, 5> b = {5,4,3,2,1};
a = b;
回答by Max
With recursion:
递归:
void copy(int *a, int *b, int b_size) {
if(b_size == 0) return;
*a = *b;
copy(++a, ++b, b_size-1);
}
I don't understand the need for recursion though, using memcpy()
instead is better.
我不明白递归的必要性,memcpy()
而是使用更好。
回答by Peter Gluck
You could use memcpy()
:
你可以使用memcpy()
:
memcpy(a, b, sizeof(a));
回答by Dennis
memcpy
works but you can use memmove
also which handily does not explode if you have over-lapping memory locations (not likely in your example, but if you the logic to a "clone" function for example it could happen).
memcpy
有效,但memmove
如果您有重叠的内存位置,您也可以使用它不会爆炸(在您的示例中不太可能,但如果您使用“克隆”功能的逻辑,例如它可能会发生)。
memmove( a, b, sizeof(a) );
Of course if you are sure about your source and destination not overlapping then memcpy
is fine.
当然,如果您确定您的源和目的地不重叠,那就没问题了memcpy
。