convert STL list<string> into vector<string> c++11

  • A+

What's the best way to convert a list into a vector?

I was thinking about a loop. But maybe there's a better way in C++11?

#include <list> #include <string> #include <vector> using namespace std;  list<string> list_string {   "one",   "two",   "three" };  vector<string> vector_string; for (auto item : list_string) {     vector_string.push_back(item); } 

In C# I could just initialize the other data type using a constructor accepting IEnumerable interface. Was curious if C++11 supports anything similar...


One of the constructors for std::vector (and indeed, for any of the standard containers), takes a pair of iterators:

template< class InputIt > vector( InputIt first, InputIt last,          const Allocator& alloc = Allocator() ); 

So you can just do:

vector<string> v(list_string.begin(), list_string.end()); 


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