セットを調べて、定義済みの基準を満たす要素を削除する必要があります。
これは私が書いたテストコードです:
#include <set>
#include <algorithm>
void printElement(int value) {
std::cout << value << " ";
}
int main() {
int initNum[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::set<int> numbers(initNum, initNum + 10);
// print '0 1 2 3 4 5 6 7 8 9'
std::for_each(numbers.begin(), numbers.end(), printElement);
std::set<int>::iterator it = numbers.begin();
// iterate through the set and erase all even numbers
for (; it != numbers.end(); ++it) {
int n = *it;
if (n % 2 == 0) {
// wouldn't invalidate the iterator?
numbers.erase(it);
}
}
// print '1 3 5 7 9'
std::for_each(numbers.begin(), numbers.end(), printElement);
return 0;
}
最初は、反復中にセットから要素を消去するとイテレータが無効になり、for ループでのインクリメントが未定義の動作になると考えていました。とはいえ、このテスト コードを実行したところ、すべてうまくいきましたが、その理由は説明できません。
私の質問: これは std セットの定義済みの動作ですか、それともこの実装固有ですか? ちなみに、ubuntu 10.04(32ビット版)でgcc 4.3.3を使用しています。
ありがとう!
提案された解決策:
これは、セットから要素を反復して消去する正しい方法ですか?
while(it != numbers.end()) {
int n = *it;
if (n % 2 == 0) {
// post-increment operator returns a copy, then increment
numbers.erase(it++);
} else {
// pre-increment operator increments, then return
++it;
}
}
編集:優先ソリューション
まったく同じですが、よりエレガントに見えるソリューションにたどり着きました。
while(it != numbers.end()) {
// copy the current iterator then increment it
std::set<int>::iterator current = it++;
int n = *current;
if (n % 2 == 0) {
// don't invalidate iterator it, because it is already
// pointing to the next element
numbers.erase(current);
}
}
while 内に複数のテスト条件がある場合、それらのそれぞれが反復子をインクリメントする必要があります。イテレータが1 か所でのみインクリメントされ、コードがエラーを起こしにくくなり、読みやすくなるため、このコードの方が気に入っています。