Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Ignoring the Voices: C++11 Example - Initialization Lists
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
// Our method which takes an initialization list parameter
template<class T> void MyFunction(initializer_list<T> values)
{
cout << "Number of items in initializer list: " << values.size() << endl;
for (auto i = begin(values); i < end(values); ++i)
{
cout << *i << " ";
}
cout << endl;
}
int main()
{
// Good old fashioned array initialization
int a[] = { 1, 2, 3 };
for (auto i = begin(a); i != end(a); ++i)
{
cout << *i << endl;
}
// Initializing a vector with an initialization list
vector<string> b({ "Hello", "World" });
for (auto i = begin(b); i != end(b); ++i)
{
cout << *i << endl;
}
// Initializing a map with an initialization list
map<int, vector<string>> c({
{1, { "Ignoring", "The", "Voices" } },
{2, { "In", "My", "Head" } }
});
for (auto i = begin(c); i != end(c); ++i)
{
cout << i->first << " :";
for (auto s = begin(i->second); s != end(i->second); ++s)
{
cout << " " << *s;
}
cout << endl;
}
MyFunction<int>({ 5, 4, 3, 2, 1 });
MyFunction<string>({ "I", "Love", "Initializer", "Lists" });
}
Owner

dazfuller commented Nov 10, 2011

Compiled as follows with GCC 4.6.1 on Ubuntu 11.10

g++ -std=c++0x -Wall -Werror -o initializer_lists initializer_lists.cpp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment