- Learning C++ Functional Programming
- Wisnu Anggoro
- 280字
- 2021-07-02 20:51:36
Returning an iterator using non-member begin() and end() function
Prior to modern C++, to iterate a sequence, we call the begin() and end() member method of each container. For array, we can iterate its element by iterating the index. Since C++11, the language has a non-member function--begin() and end()--to retrieve the iterator of the sequence. Let's suppose we have an array of the following elements:
int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
When the language doesn't have the begin() and end() function, we need to iterate the elements of the array using the index we can see in the following lines of code:
for (unsigned int i = 0; i < sizeof(arr)/sizeof(arr[0]); ++i)
// Do something to the array
Fortunately, using the begin() and end() function, we can refactor the preceding for loop to become as follows:
for (auto i = std::begin(arr); i != std::end(arr); ++i)
// Do something to the array
As we can see, the use of the begin() and end() function creates a compact code since we don't need to worry about the length of the array because the iterator pointer of begin() and end() will do it for us. For comparison, let's take a look at the following begin_end.cpp code:
/* begin_end.cpp */
#include <iostream>
auto main() -> int
{
std::cout << "[begin_end.cpp]" << std::endl;
// Declaring an array
int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Displaying the array elements
// using conventional for-loop
std::cout << "Displaying array element using conventional for-
loop";
std::cout << std::endl;
for (unsigned int i = 0; i < sizeof(arr)/sizeof(arr[0]); ++i)
std::cout << arr[i] << " ";
std::cout << std::endl;
// Displaying the array elements
// using non-member begin() and end()
std::cout << "Displaying array element using non-member begin()
and end()";
std::cout << std::endl;
for (auto i = std::begin(arr); i != std::end(arr); ++i)
std::cout << *i << " ";
std::cout << std::endl;
return 0;
}
To prove the preceding code, we can compile the code, and, when we run it, the following output should be displayed on the console screen:

As we can see in the screenshot, we've got the exact same output when we use the conventional for-loop or begin() and end() functions.
- Web前端開發(fā)技術(shù):HTML、CSS、JavaScript(第3版)
- Java應(yīng)用與實(shí)戰(zhàn)
- 深入理解Django:框架內(nèi)幕與實(shí)現(xiàn)原理
- Java Web基礎(chǔ)與實(shí)例教程
- Apache Karaf Cookbook
- Scala編程實(shí)戰(zhàn)(原書第2版)
- Angular應(yīng)用程序開發(fā)指南
- 從零開始學(xué)Android開發(fā)
- 計(jì)算機(jī)應(yīng)用技能實(shí)訓(xùn)教程
- 寫給大家看的Midjourney設(shè)計(jì)書
- Node.js區(qū)塊鏈開發(fā)
- Getting Started with JUCE
- CryENGINE Game Programming with C++,C#,and Lua
- 一步一步學(xué)Spring Boot:微服務(wù)項(xiàng)目實(shí)戰(zhàn)(第2版)
- MySQL從入門到精通