Cleanest way to copy a constant size array in c++11

前端 未结 5 1019
孤街浪徒
孤街浪徒 2020-12-13 17:29

I often find myself wanting to copy the contents of arrays that have a constant size, I usually just write something along the lines of:

float a[4] = {0,1,2,         


        
相关标签:
5条回答
  • 2020-12-13 17:45

    Below method works for usual arrays as well std:array.

    float a[4] = {0,1,2,3};
    float b[4];
    
    std::copy(std::begin(a), std::end(a), b);
    
    0 讨论(0)
  • 2020-12-13 17:46

    For interested in C++03 (and also C) solution - always use struct containing an array instead of solely array:

    struct s { float arr[5]; };
    

    Structs are copyable by default.

    Its equivalent in C++11 is,already mentioned, std::array<float,5>;

    0 讨论(0)
  • 2020-12-13 17:55

    The C++03 way

    Use std::copy():

    float a[4] = {0,1,2,3};
    float b[4];
    
    std::copy(a,a + 4, b);
    

    That's about as clean as it gets.

    The C++11 way

    std::copy(std::begin(a), std::end(a), std::begin(b));
    

    If you can use std::array

    With std::array you just do simple assignment:

    std::array<float,4> a = {0,1,2,3};
    auto b = a;
    
    0 讨论(0)
  • 2020-12-13 18:00
    #include <algorithm>
    std::copy_n(a, 4, b)
    
    0 讨论(0)
  • 2020-12-13 18:02

    If you use std::array instead of a built-in array (which you should), it becomes very simple. Copying an array is then the same as copying any other object.

    std::array<float,4> a = {0,1,2,3};
    std::array<float,4> b = a;
    
    0 讨论(0)
提交回复
热议问题