為了使指針和數組之類的連續數據列表操作更加簡單和安全,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;
}

