I am making a c++ problem in witch I have to write a function that takes a list. The problem is that I don't understand lists at all because I don't know how to work with pointers or iterators. Is there any way I can move all elements from that list to an array or a vector? It would make my life easier.
How to move all elements from a list to an array or a vector or anything else
You use the std::move
function.
std::list<foo> l;
std::vector<foo> r;
r.reserve(std::size(l));
std::move(std::begin(l), std::end(l), std::back_inserter(r));
If the objects you move are not of fundamental types, moving, rather than copying, will often be a lot faster.
If you have the option to create the vector<foo>
on the go, use std::move_iterator
s
std::list<foo> l;
std::vector<foo> r(std::move_iterator(std::begin(l)), std::move_iterator(std::end(l)));
std::vector<T> v;
std::copy(std::begin(l), std::end(l), std::back_inserter(v));
Where l
is your "list" (by which I assume you mean C style array) and T
is the type of things in your list. Note this copies the elements rather than moving them, but if they are basic types they cannot be moved anyway.
As pointed out by Ted Lyngmo, std::vector actually has a constructor for this already:
std::vector<T> v(std::begin(l), std::end(l));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With