insert list to end of vector

  • A+

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.

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; } 


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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: