std::initializer_list – an even better way to populate a vector

Visual Studio 2012 November CTP does provide us with support for initializer lists, even though standard library containers like vector<T> do not yet implement constructors that accept an initializer list.  However, that doesn’t stop us writing code like this to make populating containers easy:

namespace musingstudio
{
  template<typename Container>
  Container initialize( 
    std::initializer_list<typename Container::value_type> items )
  {
    return Container( items.begin(), items.end() );
  }
}

And call it like this:

auto evens = musingstudio::initialize<vector<int>>({2,4,6,8,10});

I like the way this reads “initialize vector of int( values )” – and it’s pretty efficient too, if your container supports move semantics (which the standard library containers do).

2 Comments

Filed under C++ Code

2 responses to “std::initializer_list – an even better way to populate a vector

  1. This is cool, using it right now 🙂

  2. Pingback: Use std::initializer_list in Visual C++ Compiler November 2012 CTP | BlogoSfera

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s