STL 1–迭代器std::begin()和std::end()使用
阿新 • • 發佈:2018-11-09
迭代器是一個行為類似於指標的模板類物件。只需要迭代器iter指向一個有效物件,就可以通過使用*iter解引用的方式來獲取一個物件的引用。通常會使用一對迭代器來定義一段元素,可以是任意支援迭代器物件的元素,一段元素是一個通過起始迭代器指向第一個元素,通過結束迭代器指向最後一個元素的後一個位置的元素序列。一般使用std::begin()和std::end()來獲取容器的迭代器。
#include <numeric> #include <iostream> #include <iterator> using namespace std; int main(){double data[] {2.5,4.5,6.5,5.5,8.5}; cout<<"The array contains: \n"; for(auto iter = std::begin(data) ;iter != std::end(data) ; ++iter){ cout << *iter << " "; } double total = std::accumulate(std::begin(data),std::end(data),0.0); cout <<"\n"<< total << endl;return 0; }
std::accumulate()表示計算std::begin()到std::end()之間的元素的總和,並且起始值設定為0.