Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move all elements from a list to an array or a vector or anything else

Tags:

c++

list

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.

like image 847
Adrian Avatar asked Sep 12 '25 01:09

Adrian


2 Answers

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_iterators

std::list<foo> l;
std::vector<foo> r(std::move_iterator(std::begin(l)), std::move_iterator(std::end(l)));
like image 118
Ted Lyngmo Avatar answered Sep 13 '25 14:09

Ted Lyngmo


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));
like image 27
Object object Avatar answered Sep 13 '25 14:09

Object object