diff --git a/CPP11.md b/CPP11.md index a719524..18e7488 100644 --- a/CPP11.md +++ b/CPP11.md @@ -49,6 +49,7 @@ C++11 includes the following new library features: - [std::make_shared](#stdmake_shared) - [memory model](#memory-model) - [std::async](#stdasync) +- [std::begin/end](#stdbeginend) ## C++11 Language Features @@ -874,6 +875,23 @@ auto handle = std::async(std::launch::async, foo); // create an async task auto result = handle.get(); // wait for the result ``` +### std::begin/end +`std::begin` and `std::end` free functions were added to return begin and end iterators of a container generically. These functions also work with raw arrays which do not have begin and end member functions. + +```c++ +template +int CountTwos(const T& container) { + return std::count_if(std::begin(container), std::end(container), [](int item) { + return item == 2; + }); +} + +std::vector vec = {2,2,43,435,4543,534}; +int arr[8] = {2,43,45,435,32,32,32,32}; +auto a = CountTwos(vec); // 2 +auto b = CountTwos(arr); // 1 +``` + ## Acknowledgements * [cppreference](http://en.cppreference.com/w/cpp) - especially useful for finding examples and documentation of new library features. * [C++ Rvalue References Explained](http://thbecker.net/articles/rvalue_references/section_01.html) - a great introduction I used to understand rvalue references, perfect forwarding, and move semantics. diff --git a/README.md b/README.md index 4625d72..c645ec3 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,7 @@ C++11 includes the following new library features: - [std::make_shared](#stdmake_shared) - [memory model](#memory-model) - [std::async](#stdasync) +- [std::begin/end](#stdbeginend) ## C++20 Language Features @@ -1698,6 +1699,23 @@ auto handle = std::async(std::launch::async, foo); // create an async task auto result = handle.get(); // wait for the result ``` +### std::begin/end +`std::begin` and `std::end` free functions were added to return begin and end iterators of a container generically. These functions also work with raw arrays which do not have begin and end member functions. + +```c++ +template +int CountTwos(const T& container) { + return std::count_if(std::begin(container), std::end(container), [](int item) { + return item == 2; + }); +} + +std::vector vec = {2,2,43,435,4543,534}; +int arr[8] = {2,43,45,435,32,32,32,32}; +auto a = CountTwos(vec); // 2 +auto b = CountTwos(arr); // 1 +``` + ## Acknowledgements * [cppreference](http://en.cppreference.com/w/cpp) - especially useful for finding examples and documentation of new library features. * [C++ Rvalue References Explained](http://thbecker.net/articles/rvalue_references/section_01.html) - a great introduction I used to understand rvalue references, perfect forwarding, and move semantics.