main.cpp
                        
                             · 385 B · C++
                        
                    
                    
                      
                        Raw
                      
                    
                      
                    
                        
                          
                        
                    
                    
                
                
                
            #include <iostream>
#include <functional>
std::function<int()> fibonacci()
{
    int current = 1, next = 1;
    return [=]() mutable {
        int result = current;
        next = current + (current = next);
        return result;
    };
}
int main()
{
    auto fib = fibonacci();
    for (int i = 0; i < 10; i++) {
        std::cout << fib() << std::endl;
    }
    return 0;
} 
                | 1 | #include <iostream> | 
| 2 | #include <functional> | 
| 3 | |
| 4 | std::function<int()> fibonacci() | 
| 5 | { | 
| 6 | int current = 1, next = 1; | 
| 7 | |
| 8 | return [=]() mutable { | 
| 9 | int result = current; | 
| 10 | next = current + (current = next); | 
| 11 | return result; | 
| 12 | }; | 
| 13 | } | 
| 14 | |
| 15 | int main() | 
| 16 | { | 
| 17 | auto fib = fibonacci(); | 
| 18 | |
| 19 | for (int i = 0; i < 10; i++) { | 
| 20 | std::cout << fib() << std::endl; | 
| 21 | } | 
| 22 | |
| 23 | return 0; | 
| 24 | } | 
| 25 |