Copy std::vector into std::array

前端 未结 2 883
青春惊慌失措
青春惊慌失措 2020-12-17 08:48

How do I copy or move the first n elements of a std::vector into a C++11 std::array?

相关标签:
2条回答
  • 2020-12-17 09:27

    You can use std::copy:

    int n = 2;
    std::vector<int> x {1, 2, 3};
    std::array<int, 2> y;
    std::copy(x.begin(), x.begin() + n, y.begin());
    

    And here's the live example.

    If you want to move, instead, you can use std::move:

    int n = 2;
    std::vector<int> x {1, 2, 3};
    std::array<int, 2> y;
    std::move(x.begin(), x.begin() + n, y.begin());
    

    And here's the other live example.

    0 讨论(0)
  • 2020-12-17 09:40

    Use std::copy_n

    std::array<T, N> arr;
    std::copy_n(vec.begin(), N, arr.begin());
    

    Edit: I didn't notice that you'd asked about moving the elements as well. To move, wrap the source iterator in std::move_iterator.

    std::copy_n(std::make_move_iterator(v.begin()), N, arr.begin());
    
    0 讨论(0)
提交回复
热议问题