Created
November 10, 2011 01:25
-
-
Save dazfuller/1353801 to your computer and use it in GitHub Desktop.
Ignoring the Voices: C++11 Example - Initialization Lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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" }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compiled as follows with GCC 4.6.1 on Ubuntu 11.10
g++ -std=c++0x -Wall -Werror -o initializer_lists initializer_lists.cpp