おもちゃのプログラム (post.cpp) を考えてみましょう:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int > a;
int i;
for(i=0;i<10;i++)
a.push_back(i);
auto it=a.rbegin();
while(it!=a.rend()) {
if ((*it % 2)==0) {
cout << "about to erase "<<*it<<endl;
a.erase((it++).base());
}
else {
++it;
}
}
for(auto it2=a.begin(); it2 != a.end(); it2++) {
cout << *it2 << endl;
}
return 0;
}
私がやろうとしているのは、偶数性をテストしてから(it++)
、現在のイテレータを返し、イテレータを進める必要があるため、現在の番号を削除することです。これは私が出力として得るものです:
$ ./post
about to erase 8
about to erase 6
about to erase 4
about to erase 2
about to erase 0
0
2
4
6
8
ただし、行a.erase((it++).base());
をに変更するa.erase((++it).base());
と、正しい動作が得られます。どうしてこれなの?
有用な説明: ではbase()
reverse_iterators を使用できないため、使用していerase()
ます。ベクトルを逆にして消去したいアプリケーションがあります。