How can I copy a part of an array to another array in C++?

前端 未结 5 1611
执笔经年
执笔经年 2021-02-05 10:07

This is the same question asked in C# but i need for C++

How can I copy a part of an array to another array?

Consider I\'m having

    int[] a = {         


        
相关标签:
5条回答
  • 2021-02-05 10:45

    Yes, using st standard library algorithm copy:

    #include <algorithm>
    
    int main()
    {
      int array[5] = { 1,2,3,4,5 }; // note: no int[] array
      int *b = new int[3];
      std::copy(array+1, array+4, b); 
      // copies elements 1 (inclusive) to 4 (exclusive), ie. values 2,3,4
    }
    
    0 讨论(0)
  • 2021-02-05 10:49

    Assuming you want a dynamically-allocated array as in the C# example, the simplest way is:

    std::vector<int> b(a.begin() + 1, a.begin() + 4);
    

    This also has the advantage that it will automatically release the allocated memory when it's destroyed; if you use new yourself, then you'll also need to use delete to avoid memory leaks.

    0 讨论(0)
  • 2021-02-05 10:51

    Yes, use std::copy:

    std::copy(a + src_begin_index,
              a + src_begin_index + elements_to_copy,
              b + dest_begin_index);
    

    The equivalent of your C# example would be:

    std::copy(a + 1, a + 4, b);
    
    0 讨论(0)
  • 2021-02-05 11:01

    For simple C-style arrays you can use memcpy:

    memcpy(b, &a[1], sizeof(int) * 3);
    

    This line copies sizeof(int) * 3 bytes (i.e. 12 bytes) from index 1 of a, with b as a destination.

    0 讨论(0)
  • 2021-02-05 11:02

    There is the C memcpy command, which you can use like this:

    memcpy(destinationArray, sourceArray, sizeof(*destinationArray) * elementsToCopy);
    

    There is also std::copy, which is a more C++ way of doing it:

    std::copy(source, source + elementsInSource, destination);
    

    Note that neither of these functions check to make sure that enough memory has been allocated, so use at your own risk!

    0 讨论(0)
提交回复
热议问题