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

Viewed 358

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.

3 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)));
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));

You can use std::copy to copy from one container (your list) to another container (your vector):

#include <list>
#include <vector>
#include <iostream>

int main() {
    std::list<int> list = {1, 2, 3, 4, 5};
    std::vector<int> vec;
    std::copy(std::begin(list), std::end(list), std::back_inserter(vec));

    for (auto element: vec) {
        std::cout << element << ", ";
    }
    std::cout << "\n";
}

https://godbolt.org/z/73rj494f4


You can also manually copy elements from one container to the other. However, while this is maybe easier to understand, it is not as elegant:

#include <list>
#include <vector>
#include <iostream>

int main() {
    std::list<int> list = {1, 2, 3, 4, 5};
    std::vector<int> vec;
    vec.reserve(list.size());  // Optional.

    // Copy the elements manually
    for (auto element: list) {
        vec.push_back(element);
    }

    // Manually print the elements in vec.
    for (auto element: vec) {
        std::cout << element << ", ";
    }
    std::cout << "\n";
}

https://godbolt.org/z/faf8ahr75

Related