TheStrangeQuark
TheStrangeQuark

Reputation: 2405

insert list to end of vector

Is there an easy way to insert an entire list to the end of a vector without inserting the front value and popping it for the entire list? Right now, I'm doing thing:

std::vector<int> v({1,2,3});
std::list<int> l({5,7,9});
for (int i=0; i<3; i++) {
    v.push_back(l.front());
    l.pop_front();
}

I'm hoping for some way to easily just iterate through the list and insert it into the vector.

Upvotes: 5

Views: 4496

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106086

While the question illustrated int element types, that might have been a simplification while preparing an example, or other readers might find this Q&A when wanting to move non-copyable elements from the list, or types likes std::string that can often1 be moved faster than copied. To move elements, use:

v.insert(v.end(),
         std::move_iterator{l.begin()}, std::move_iterator{l.end()});
l.clear();

1 in string's case - when longer than any internal Short-String-Optimisation buffer and therefore using dynamically allocated memory

Upvotes: 6

gchen
gchen

Reputation: 1173

Another way -- maybe you can just use the initializer list directly

v.insert(v.end(), {5,7,9});

You can also use std::copy

std::copy(l.begin(), l.end(), std::back_inserter(v));
l.clear();

Upvotes: 2

bcr
bcr

Reputation: 950

You need to insert at the end of v. Both vector and list have iterators so its pretty straight forward.

You can replace your for loop with this single line:

v.insert(v.end(), l.begin(), l.end());

Here is the updated code:

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

int main() {
    std::cout << "Hello, World!\n";
    std::vector<int> v({1,2,3});
    std::list<int> l({5,7,9});

    v.insert(v.end(), l.begin(), l.end());
    l.clear();

    for (int i : v) {
        std::cout << i << " ";
    }

    std::cout << std::endl;

    return 0;
}

output:

Hello, World!
1 2 3 5 7 9 
Program ended with exit code: 0

Upvotes: 6

Related Questions