Есть ли функция для копирования массива в C/С++?
Я программист Java, изучающий C/С++. Поэтому я знаю, что Java имеет такую функцию, как System.arraycopy(); для копирования массива. Мне было интересно, есть ли функция на C или С++ для копирования массива. Мне удалось найти реализацию для копирования массива, используя для цикла, указатели и т.д. Есть ли функция, которую я могу использовать для копирования массива?
ОТВЕТЫ
Ответ 1
Так как С++ 11, вы можете копировать массивы непосредственно с помощью std::array :
Вот документация о std:: array
Ответ 2
Поскольку вы попросили решение C++.
Ответ 3
Как упоминалось выше, в C вы использовали бы memcpy . Обратите внимание, однако, что это делает необработанную копию памяти, поэтому, если ваши структуры данных имеют указатель на себя или друг на друга, указатели в копии по-прежнему будут указывать на исходные объекты.
В С++ вы также можете использовать memcpy , если ваши члены массива POD (то есть, по существу, типы, которые вы также могли бы использовать без изменений в C), но в целом memcpy не будет разрешено. Как упоминалось выше, используемая функция std::copy .
Сказав, что на С++ вы редко должны использовать необработанные массивы. Вместо этого вы должны использовать один из стандартных контейнеров ( std::vector является самым близким к встроенному массиву, а также я думаю, что ближе всего к массивам Java — ближе, чем простые массивы С++, действительно, — но std::deque или std::list может быть более уместным в некоторых случаях) или, если вы используете С++ 11, std::array , который очень близок к встроенным массивам, но с семантикой значений, как и другие типы С++. Все типы, упомянутые здесь, могут быть скопированы путем назначения или создания копии. Кроме того, вы можете «перекрестно копировать» из opne в другой (и даже из встроенного массива), используя синтаксис итератора.
Это дает обзор возможностей (я предполагаю, что все соответствующие заголовки включены):
Ответ 4
Вы можете использовать memcpy() ,
memcpy() копирует значения num байтов из местоположения, на которое указывает source , непосредственно в блок памяти, на который указывает destination .
Если перекрытие destination и source перекрывается, вы можете использовать memmove() .
memmove() копирует значения num байтов из местоположения, на которое указывает source , в блок памяти, на который указывает destination . Копирование происходит, как если бы использовался промежуточный буфер, позволяя месту назначения и источнику перекрываться.
Ответ 5
Используйте memcpy в C, std::copy в С++.
Ответ 6
В C вы можете использовать memcpy . В С++ используйте std::copy из заголовка <algorithm> .
Ответ 7
в С++ 11 вы можете использовать Copy() , который работает для контейнеров std
Ответ 8
Я даю здесь два способа справиться с массивом, для языков C и С++. memcpy и copy оба применимы на С++, но копировать нельзя использовать для C, вы должны использовать memcpy, если вы пытаетесь скопировать массив в C.
Ответ 9
Во-первых, поскольку вы переключаетесь на С++, рекомендуется использовать вектор вместо традиционного массива. Кроме того, чтобы скопировать массив или вектор, std::copy — лучший выбор для вас.
Посетите эту страницу, чтобы узнать, как использовать функцию копирования: http://en.cppreference.com/w/cpp/algorithm/copy
Ответ 10
Просто включите стандартную библиотеку в свой код.
Размер массива будет обозначен как n
Ваш старый массив
Объявите новый массив, в который нужно скопировать старое значение массива
Ответ 11
Мне нравится ответ Эд С., но это работает только для массивов фиксированного размера, а не тогда, когда массивы определены как указатели.
Итак, решение C++, где массивы определены как указатели:
Примечание: нет необходимости вычитать buffersize с 1:
1) Копирует все элементы в диапазоне [первый, последний), начиная с первого и заканчивая последним — 1
Is there a function to copy an array in C/C++?
I know that Java has a function System.arraycopy(); to copy an array. I was wondering if there is a function in C or C++ to copy an array. I was only able to find implementations to copy an array by using for loops, pointers, etc. But is there a library function that I can use to copy an array?
13 Answers 13
Since you asked for a C++ solution.
Since C++11, you can copy arrays directly with std::array :
As others have mentioned, in C you would use memcpy . Note however that this does a raw memory copy, so if your data structures have pointer to themselves or to each other, the pointers in the copy will still point to the original objects.
In C++ you can also use memcpy if your array members are POD (that is, essentially types which you could also have used unchanged in C), but in general, memcpy will not be allowed. As others mentioned, the function to use is std::copy .
Having said that, in C++ you rarely should use raw arrays. Instead you should either use one of the standard containers ( std::vector is the closest to a built-in array, and also I think the closest to Java arrays — closer than plain C++ arrays, indeed —, but std::deque or std::list may be more appropriate in some cases) or, if you use C++11, std::array which is very close to built-in arrays, but with value semantics like other C++ types. All the types I mentioned here can be copied by assignment or copy construction. Moreover, you can "cross-copy" from opne to another (and even from a built-in array) using iterator syntax.
This gives an overview of the possibilities (I assume all relevant headers have been included):
How to Copy an Array in C++
This is an array of ten characters from the letters, ‘F’ to ‘O’. The name of this array is arr1. Consider the following array:
The name of this array is arr2. Notice that both contents, are the same. arr2 would be a deep copy of arr1 if both initializer_lists are in different regions in the computer’s memory. This article explains, manual deep copying of the array, and automatic deep copying of the array, in C++.
Article Content
Manual Deep Copying of the Array
With this approach, two arrays of the same size are created. The first one has content while the second one does not have content. The content of the first one is copied into the second one using the for-loop. The following program illustrates this:
#include <iostream>
using namespace std ;
int main ( ) {
#define size 10
char arr1 [ ] = { ‘F’ , ‘G’ , ‘H’ , ‘I’ , ‘J’ , ‘K’ , ‘L’ , ‘M’ , ‘N’ , ‘O’ } ;
char arr2 [ size ] ;
for ( int i = 0 ; i < size ; i ++ )
arr2 [ i ] = arr1 [ i ] ;
The first line of the program includes the C++ iostream header (library) for input and output. This first line is a directive. The second line is not a directive. It is a statement. It insists that any name not preceded by std:: is of the standard namespace. Thereafter is the C++ main function.
The first line in the main() function is a directive. It defines the size of both arrays, to be 10. It does not end with a semicolon. It ends with the press of the keyboard Enter Key ‘\n’ . This line could equally have been “int size = 10;”. The line after is a statement that defines the first array. The line following is the declaration of the second array, without practical initialization, but with the same size.
The next code segment in the main function, does the copy, element by element, from the first to the second array.
The following two code segments can be added, to print both array contents at the terminal (console):
for ( int i = 0 ; i < size ; i ++ )
cout << arr1 [ i ] << ‘ ‘ ;
cout << endl ;
for ( int i = 0 ; i < size ; i ++ )
cout << arr2 [ i ] << ‘ ‘ ;
cout << endl ;
The output should be,
Automatic Deep Copying of the Array
Here, the std::copy() function, of the C++ algorithm library is used. This means, the algorithm header (library) has to be included into the program. There is no need to copy, element by element, here. The prototype of the std::copy() function is:
template < class InputIterator, class OutputIterator >
constexpr OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result ) ;
The first argument is an iterator that points to the first element of the source container (list). The second argument is an iterator that points just beyond the last element of the source container. The third argument is an iterator that points to the first element of the empty destination container, which should already have been declared.
This syntax can be interpreted for arrays with the following prototype:
template < class InputIterator, class OutputIterator >
constexpr OutputIterator copy ( arr1, pointer — to — just — past — arr1, arr2 ) ;
pointer-to-just-past-arr1 is the same as, arr1 + size. So, the following program, does automatic deep copying of one array to another:
#include <iostream>
#include <algorithm>
int main ( ) {
int size = 10 ;
char arr1 [ ] = { ‘F’ , ‘G’ , ‘H’ , ‘I’ , ‘J’ , ‘K’ , ‘L’ , ‘M’ , ‘N’ , ‘O’ } ;
char arr2 [ size ] ;
copy ( arr1, arr1 + size, arr2 ) ; //auto copying
Note the inclusion of the algorithm library. “int size = 10;” has been used, instead of “char arr2[size];”. Note that the arrays still had to be of the same size but with the second one empty. The automatic copying statement is:
The function did not have to be preceded by “std::” , since there is “using namespace std;” at the top of the program.
The following two code segments can be added to print both array contents at the terminal (console):
for ( int i = 0 ; i < size ; i ++ )
cout << arr1 [ i ] << ‘ ‘ ;
cout << endl ;
for ( int i = 0 ; i < size ; i ++ )
cout << arr2 [ i ] << ‘ ‘ ;
cout << endl ;
The output should be,
Conclusion
In C++ an array can be copied manually (by hand) or automatically using the std::copy() function from the C++ algorithm library. In computer programming, there is shallow copying and there is deep copying. Shallow copying is when two different array names (old and new) refer to the same content in memory. Deep copying is when the two different array names refer to two independent, but same content, in memory. This article has dealt with deep copying and not shallow copying.
With manual deep copying approach, two arrays of the same size are created. The first one has content, while the second one does not have content. The content of the first one is copied to the second one, using the for-loop.
Automatic deep copying of one array to another in C++ involves the std::copy() function of the C++ algorithm library. This means, the algorithm header (library) has to be included into the program. There is no need to copy element by element with the for-loop in this case since copying is automatic. The prototype for the std::copy() function, interpreted for the array, is:
template < class InputIterator, class OutputIterator >
constexpr OutputIterator copy ( arr1, pointer — to — last — element — of — arr1, arr2 ) ;
Копирование одного массива в другой с помощью указателей
Я должен использовать указатели для копирования значений одного массива в другой. Проблема в том, что мне не разрешено использовать операторы ‘[]’, что делает это более сложным для меня. Вот моя попытка:
Более простой способ сделать это — поместить p2 [i] = p1 [i] в цикл, но я не могу этого сделать. Любая помощь приветствуется.
Решение
Стандартный способ реализации вашей функции заключается в следующем:
Чтобы быть немного более явным, это так же, как:
Другие решения
В реальном коде вы бы использовали std::copy прежде чем даже думать о переписывании такой простой вещи самостоятельно.
Вот полный пример:
Тем не менее, ваш вопрос говорит о том, что вы «не разрешено использовать» что-то, что звучит очень похоже на домашнее задание. В этом случае вы можете посмотреть на возможные реализации std::copy чтобы понять, как это сделать. Вот один из способов: