c++11新特性之begin,end和基於范圍的for循環


為了使指針和數組之類的連續數據列表操作更加簡單和安全,c++11引入了用於獲取

數組,列表,鏈表之類的序列數據首,尾地址的標准通常函數begin,end和范圍的for循環語句

begin返回指向序列首元素的指針,end返回指向序列最后一個元素后一個位置的指針

0 1 2 3 4 5 null

begin返回0這個位置的指針,end返回5后面的指針

范圍for語句用於遍歷數組和STL容器或其他序列

begin(序列)

end(序列)

for(變量聲明:序列)

循環體

下面做一個演示吧

#include<iostream>
#include<string>
using namespace std;

int main()
{
	int a[10] = {1,2,3,4,5,6,7,8,9,10};
	string s("hello world!");
	int n = 0;
	for(int i:a)
	cout << i << "\t";
	cout << endl;
	
	for(auto& i:a) //通過引用改變a數組的值 
	i *= i;
	
	for(int *p = begin(a);p != end(a);p++)
	cout << *p << "\t";
	cout << endl;
	
	for(auto &c:s)
	{
		n++;
		c = toupper(c);//改為大寫 
	}
	
	cout << "s have:" << n << " chars" << endl;
	for(auto p = begin(s);p != end(s);p++)
	cout << *p;
	return 0;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM