イテレータとはコンテナ内での要素の位置を指すもので、ポインタのように扱うことができる。イテレータを使用することで、コンテナの種類に依存しないで処理を共通化できる。
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> x = {0, 1, 2, 3, 4};
// begin()でコンテナ内の先頭要素を指す
auto it = x.begin();
cout << *it << endl;
++it;
cout << *it << endl;
return 0;
}
$ g++ -o sample sample.cpp && ./sample
0
1
end()は要素の1つ先となる。
vector<int> x = {0, 1, 2, 3, 4};
for (auto it = x.begin(); it != x.end(); ++it) {
cout << *it << endl;
}
return 0;
この性質によってコンテナの種類に依存せず algorithmで提供される機能を使用できる。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> x = {0, 1, 2, 3, 4};
auto n = std::count_if(x.begin(), x.end(), [](const int v){
if (v <= 0) {
return false;
}
if (v % 2 != 0){
return false;
}
return true;
});
cout << n << endl;
return 0;
}