Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert list to end of vector

Tags:

c++

stl

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.

like image 924
TheStrangeQuark Avatar asked Dec 08 '22 15:12

TheStrangeQuark


2 Answers

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
like image 199
bcr Avatar answered Dec 10 '22 03:12

bcr


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

like image 30
Tony Delroy Avatar answered Dec 10 '22 03:12

Tony Delroy