次のC++ STLプログラムでは、ファンクタNthを定義し、n回目にrevokeされた場合はtrueを返します。そして、汎用アルゴリズムremove_ifに変換します。奇妙な。ファンクタを述語として使用するC++ STLプログラム
コード:
#include <iostream>
#include <list>
#include <algorithm>
#include "print.hpp"
using namespace std;
class Nth{
private:
int nth,ncount;
public:
Nth(int n):nth(n),ncount(0){}
bool operator()(int)
{
return ++ncount == nth;
}
};
int main()
{
list<int> col;
for (int i = 1;i <=9 ;++i)
{
col.push_back(i);
}
PRINT_ELEMENTS(col,"col : ");
list<int>::iterator pos;
pos = remove_if(col.begin(),col.end(),
Nth(3));
col.erase(pos,col.end());
PRINT_ELEMENTS(col,"nth removed : ");
}
print.hpp:
#include <iostream>
template <class T>
inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="")
{
typename T::const_iterator pos;
std::cout << optcstr;
for (pos=coll.begin(); pos!=coll.end(); ++pos) {
std::cout << *pos << ' ';
}
std::cout << std::endl;
}
私は、Microsoft Visual Studio 2008でそれを実行し、私は結果を得る:それはその要素3と6を削除 を私は望んでいない。私は3つだけ削除されると思った。 誰かが私のために解釈できますか?ありがとうございました。
より正確には、OPが達成したいことはまだ可能です。状態は外部化され、変更可能な参照の形で述部に渡されます。与えられた述語のすべてのコピーは元のものと同じ変更可能な状態を共有します。 –