Input_iterator,find_if和模数

时间:2010-08-06 08:53:55

标签: c++ boost stl iterator

我实现了一个迭代器,它有Fibonacci数作为输出。在我的主要()中,我想找到一个可分数为17的数字(它是34)。为什么我的find_if语句不起作用。

谢谢!

  #include <boost/operators.hpp>
  #include <algorithm>
  #include <tr1/functional>

    struct FibIter: boost::input_iterator_helper<FibIter,unsigned long long> {

 //typedef value_type unsigned long long;
 FibIter(value_type l=0):counter(0), fib0(0),fib1(1){
  while(l!=counter)
   ++(*this);
 }

 value_type operator*() const {return fib0;}
 FibIter& operator++() {
  ++counter; 
  value_type fnew = fib0+fib1;
  fib0 = fib1;
  fib1 = fnew;
  return *this;
  }
 bool operator==(FibIter const &other)const {
  return counter == other.counter;
 }


    private:
 value_type counter;
 value_type fib0, fib1;
    };

    using namespace std;
    using namespace tr1;
    using namespace placeholders;

    int main() {
 FibIter found = find_if(FibIter(), FibIter(100),bind(not2(modulus<unsigned long long>()),_1,17ULL));
    }

4 个答案:

答案 0 :(得分:0)

bind(not2(modulus<unsigned long long>()),_1,17ULL)

应该是

not1(bind(modulus<unsigned long long>(),_1,17ULL))

答案 1 :(得分:0)

我想如果从第一个数字0开始,find会返回它(模数(0,17)= 0 )。

答案 2 :(得分:0)

好的我用!boost :: bind(...)而不是tr1 :: bind。

来解决它

答案 3 :(得分:0)

首先,您可以在构造函数中使用std::advance(*this,l);而不是while循环。但!你的方法非常低效,因为它需要计算斐波那契序列两次:一个知道什么是最后一个斐波那契数,第二个实际到达那里{{1客户端代码使用它。

我认为更好的方法是将构造函数中的++ Fibonacci数的索引存储在私有成员中,并在每个last之后将计数器与它进行比较。它可以通过这样的方式从已存在的++字段中重用:

让默认构造函数将Fibonacci迭代器初始化为indexfib0 = 0以及fib1 = 1。另一个构造函数(参数)将创建一个虚拟迭代器,它只包含序列的最后一个索引,其他字段无效。这一个迭代器将是“一个接一个”的迭代器,仅用于索引比较,而不是读取值。

所以这是我的解决方案:

index = 0

输出:

#include <iterator>

class Fibonacci : public iterator<input_iterator_tag, int>
{
    unsigned index;
    value_type fib0, fib1;
 public:
    Fibonacci(): index(0), fib0(0), fib1(1) { }
    explicit Fibonacci(unsigned last): index(last), fib0(0), fib1(0) { }
    bool operator == (const Fibonacci& other) { return index == other.index; }
    bool operator != (const Fibonacci& other) { return !(*this == other); }
    value_type operator * () const { return fib0; }
    Fibonacci& operator ++ () {
        ++index;
        value_type fnew = fib0 + fib1;
        fib0 = fib1; fib1 = fnew;
        return *this;
    }
    Fibonacci operator ++ (int) {
        Fibonacci current(*this);
        ++(*this);
        return current;
    }
};

#include <iostream>
#include <algorithm>

int main()
{
    using namespace std;
    ostream_iterator<int> out(cout, "; ");
    cout << "Fibonacci numbers from 0th to 19th:\n";
    copy(Fibonacci(), Fibonacci(20), out);
    cout << endl;
}

正如您所看到的,在我的示例中还有更多的代码重用:我通过调用它们来重用其他运算符中的运算符。

当然它仅适用于符合Fibonacci numbers from 0th to 19th: 0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89; 144; 233; 377; 610; 987; 1597; 2584; 4181; 的数字。最好将其重写为使用多个精确数字(例如GMP库)。

相关问题