Tag Archives: C++11

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

Variadic Templates – example that simplifies populating a vector

I was hoping that Visual Studio 2012 would allow us to initialise a std::vector; like this, especially with the November CTP:

std::vector<int> items = { 1, 2, 3, 4, 5 };

However, although the November CTP includes support for variadic templates and uniform initialisation, they haven’t yet decorated all standard templates with initializer lists as needed for the above. That tempted me to write a simple variadic template to avoid having to write code like this ever again:

std::vector<int> items;
items.push_back(0);
items.push_back(1);
items.push_back(2);

By writing this:

namespace musingstudio
{
  template<typename T, typename U, typename ...Args>
  void push_back(std::vector<T>& items, U item, Args ...args)
  {
    items.push_back(item);
    push_back( items, args... );
  }

  template<typename T, typename U>
  void push_back(std::vector<T>& items, U item)
  {
    items.push_back(item);
  }
}

We can then write this:

std::vector<int> items;
musingstudio::push_back( items, 0,1,2,3,4,5 );

Obviously, this is less efficient than implementing a constructor that takes initializer lists, but it’s more fun than repeatedly typing push_back the C++98/03 way.

Leave a comment

Filed under C++ Code