New features of C++11 (11) - standard library functions begin and end

How to iterate through the elements of an array


Suppose there is an array:


int  a1[]{ 1 , 2 , 3 , 4 , 5 };    


Iterate over all elements of an array like this:


for(unsignedinti=0;i<sizeof(a1)/sizeof(a1[0]);++i){        

       cout << a1[i] << endl;

 }


This can also be done like this:


for(int* p1 = a1; p1 != (a1 +sizeof(a1)/sizeof(a1[0]));++p1){ 

       cout << *p1 << endl;

 }


It still takes a little skill.


Look at the code below.


void output(int data[]){

   for(unsignedinti=0;i<sizeof(data)/sizeof(data[0]);i++){        

       cout << data[i] << endl;

   }

}


While the code compiles (possibly with warnings), it doesn't work. The reason is that data is actually a pointer, so the size of the array cannot be calculated correctly.


Standard library functions begin and end


The main difficulty of the above code is the calculation of the end address of the array. To ease the difficulty here, C++11 introduced begin and end functions. The code using begin and end is as follows:


for(int* p1 = begin(a1); p1 != end(a1); ++p1){

       cout << *p1 << endl;

 }


The code is concise and the purpose is clear.


Back to the function above:


void output(int data[]){

   for(int* p = begin(data); p != end(data); p++){

       cout << *p << endl;

   }

}


照样清晰,照样简练,但是不能通过编译。这样就避免了错误的发生。


作者观点


begin并没有绝对的必要性,恐怕只是作为end的对称而存在的。


觉得本文有帮助?请分享给更多人。
阅读更多更新文章,请扫描下面二维码,关注微信公众号【面向对象思考】

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325915795&siteId=291194637