リバースイテレータでリストを回しながら、 時折 erase を行う
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdlib> | |
#include <list> | |
using namespace std; | |
class Hoge | |
{ | |
char c; | |
int value; | |
public: | |
Hoge(); | |
Hoge(char _c, int _value); | |
void print(); | |
bool check(int _val); | |
}; | |
Hoge::Hoge() | |
{ | |
char c = '0'; | |
value = 0; | |
}; | |
Hoge::Hoge(char _c, int _value) | |
{ | |
c = _c; | |
value = _value; | |
}; | |
void Hoge::print() | |
{ | |
cout << "name: " << this->c << " value: " << this->value << endl; | |
}; | |
bool Hoge::check(int _val) | |
{ | |
if(this->value == _val) return true; | |
else return false; | |
}; | |
int main() | |
{ | |
cout << "hello world" << endl; | |
list<Hoge> hogelist; | |
list<Hoge>::reverse_iterator hoge_ri; | |
// 10個のHogeを用意 | |
for(int i = 0; i < 10; i++) | |
{ | |
Hoge hoge( i + 65, i * 100); | |
hogelist.push_back(hoge); | |
} | |
// まずは初期状態をプリントしておく | |
hoge_ri = hogelist.rbegin(); | |
while( hoge_ri != hogelist.rend() ) | |
{ | |
hoge_ri->print(); | |
hoge_ri++; | |
} | |
// 一個ずつ数値を消していく | |
while(true) | |
{ | |
int value; | |
cout << "please input INTEGER number you want to remove: " << endl; | |
cout << "or input -1 to end: " ; | |
cin >> value; | |
if( value == -1 ) break; | |
hoge_ri = hogelist.rbegin(); | |
while(hoge_ri != hogelist.rend()) | |
{ | |
if(hoge_ri->check(value)) | |
{ | |
hogelist.erase(--(hoge_ri.base())); | |
cout << "###erase### " << value << endl; | |
} | |
else | |
{ | |
hoge_ri->print(); | |
hoge_ri++; | |
} | |
} | |
// 通常のイテレータを使う場合の書き方 | |
//list<Hoge>::iterator i = hogelist.begin(); | |
//while(i != hogelist.end()) | |
//{ | |
// if(i->check(value)) | |
// { | |
// cout << "###erase### " << value << endl; | |
// i = hogelist.erase(i); | |
// } | |
// else | |
// { | |
// i->print(); | |
// i++; | |
// } | |
//} | |
} | |
cout << "fin" << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment