关于Set元素的删除解决方法
关于Set元素的删除
STL中的Set模板 如何进行for循环里面的删除呢
比如我现在有一个set的整数集合,我需要删除所有能被2整除的数,如何删除??~
------解决方案--------------------
#include <set>
#include <functional>
#include <iostream>
#include <iterator>
using namespace std;
struct IsEvenNumber : public unary_function<int,bool>
{
bool operator() (int i)
{
return 0 == (i % 2);
}
};
int main()
{
set<int> s;
for (int i = 0; i < 10; ++i)
{
s.insert(i);
}
IsEvenNumber prd;
bool bExit = false;
while (!bExit)
{
bool bFind = false;
set<int>::iterator b = s.begin();
set<int>::iterator e = s.end();
for (; b != e; ++b)
{
if (prd(*b))
{
s.erase(b);
bFind = true;
break;
}
}
bExit = !bFind;
}
copy(s.begin(), s.end(), ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
------解决方案--------------------
STL中的Set模板 如何进行for循环里面的删除呢
比如我现在有一个set的整数集合,我需要删除所有能被2整除的数,如何删除??~
------解决方案--------------------
#include <set>
#include <functional>
#include <iostream>
#include <iterator>
using namespace std;
struct IsEvenNumber : public unary_function<int,bool>
{
bool operator() (int i)
{
return 0 == (i % 2);
}
};
int main()
{
set<int> s;
for (int i = 0; i < 10; ++i)
{
s.insert(i);
}
IsEvenNumber prd;
bool bExit = false;
while (!bExit)
{
bool bFind = false;
set<int>::iterator b = s.begin();
set<int>::iterator e = s.end();
for (; b != e; ++b)
{
if (prd(*b))
{
s.erase(b);
bFind = true;
break;
}
}
bExit = !bFind;
}
copy(s.begin(), s.end(), ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
------解决方案--------------------