2014-01-22 150 views
13

如何将std::vector<T>的第一个n元素复制或移动到C++中11 std::array<T, n>将std :: vector复制到std :: array

+12

['std :: copy_n'](http://en.cppreference.com/w/cpp/algorithm/copy_n)。 –

+0

你想复制或移动?这些是不同的事情。 – juanchopanza

+0

根据':: std :: vector'包含什么,也可以使用':: std :: memcpy'和':: std :: memmove'。 – user1095108

回答

22

使用std::copy_n

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

编辑:我没有注意到你问有关移动元素。要移动,请在std::move_iterator中包装源迭代器。

std::copy_n(std::make_move_iterator(v.begin()), N, arr.begin()); 
+0

这里N是const?数组 N应该是const。 –

+0

@notbad是的,'N'是常量(我猜应该在问题中使用'n') – Praetorian

+3

还有'std :: move'。可悲的是,不是'std :: move_n'。 –

4

您可以使用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()); 

而且here的活例子。

如果你想动,相反,你可以使用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()); 

而且here的另一个活生生的例子。

+0

'n'怎么样?它不应该是'std :: copy(x.begin(),x.begin()+ n,y.begin());'? – legends2k

+0

而不是使用'n'这样的变量,使用'x.size()'会更好吗? –

相关问题