Skip to content

Instantly share code, notes, and snippets.

@izmhr
Last active August 29, 2015 14:08
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save izmhr/c6960d91720d335d1d1f to your computer and use it in GitHub Desktop.
リバースイテレータでリストを回しながら、 時折 erase を行う
#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