Skip to content

Instantly share code, notes, and snippets.

@mnzk
Last active August 29, 2015 13:56
Show Gist options
  • Save mnzk/9325893 to your computer and use it in GitHub Desktop.
Save mnzk/9325893 to your computer and use it in GitHub Desktop.
Boost.Coroutineでフィボナッチ + itertoolsっぽい(?)drop
/*
* C++11 (VisualStudio 2013 Express Edition)
* boost 1.55.0
*/
#include <iostream>
#include <boost/coroutine/all.hpp>
#include <boost/range/irange.hpp>
#include <boost/multiprecision/cpp_int.hpp>
template<typename T>
class fibo {
T pre_;
T current_;
typedef typename boost::coroutines::coroutine<T>::pull_type pull_type;
typedef typename boost::coroutines::coroutine<T>::push_type push_type;
typedef typename boost::coroutines::pull_coroutine<T> generator;
fibo() : pre_(T(0)), current_(T(1)){}
public:
void operator()(push_type& yield){
for (;;){
yield(current_);
pre_ += current_;
std::swap(pre_, current_);
}
}
static generator generate(){
return pull_type(fibo<T>());
}
};
template<typename T>
class itertools {
typedef typename boost::coroutines::pull_coroutine<T>::iterator iterator;
public:
static iterator drop(const int n, iterator& it){
for (int i = 0; i < n; ++i, ++it);
return it;
}
};
void fibo_int(){
std::cout << "-- fibo<int> --" << std::endl;
typedef itertools<int> itts;
auto gen = fibo<int>::generate();
auto it = itts::drop(10, boost::begin(gen));
for (int i : boost::irange(10, 21)){
std::cout << i << " : " << *(it++) << std::endl;
}
}
void fibo_bigint(){
std::cout << "-- fibo<bigint> --" << std::endl;
typedef boost::multiprecision::cpp_int bigint;
typedef itertools<bigint> itts;
auto gen = fibo<bigint>::generate();
auto it = itts::drop(100, boost::begin(gen));
for (int i : boost::irange(100, 111)){
std::cout << i << " : " << *(it++) << std::endl;
}
}
int main(){
fibo_int();
fibo_bigint();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment