Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(266)

Side by Side Diff: base/cpp101/fibonacci.cc

Issue 23702018: Example solution for C++ 101 Exercise 2 (callbacks, and bind) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Sync to 224002 Created 7 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « base/base.gyp ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <stdio.h>
6
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/callback.h"
10 #include "base/strings/string_number_conversions.h"
11
12 namespace {
13
14 struct FibonacciState {
15 FibonacciState() : i(0), j(1) {}
16
17 int i, j;
18 };
19
20 int ComputeNextFibonacciNumber(FibonacciState* state) {
21 int next = state->i + state->j;
22 state->i = state->j;
23 state->j = next;
24 return state->i;
25 }
26
27 base::Callback<int()> MakeFibonacciClosure() {
28 scoped_ptr<FibonacciState> state(new FibonacciState);
29 return base::Bind(&ComputeNextFibonacciNumber, base::Owned(state.release()));
30 }
31
32 } // namespace
33
34 int main(int argc, char* argv[]) {
35 if (argc <= 1) {
36 printf("%s: missing operand\n", argv[0]);
37 return -1;
38 }
39
40 int n = 0;
41 if (!base::StringToInt(argv[1], &n) || n < 0) {
42 printf("%s: invalid n `%s'\n", argv[0], argv[1]);
43 return -1;
44 }
45
46 base::Callback<int()> fibonacci_closure1 = MakeFibonacciClosure();
47 base::Callback<int()> fibonacci_closure2 = MakeFibonacciClosure();
48 for (int i = 0; i < n; ++i) {
49 int j = fibonacci_closure1.Run();
50 int k = fibonacci_closure2.Run();
51 DCHECK_EQ(j, k);
52 printf("F_%d = %d\n", i, j);
53 }
54
55 return 0;
56 }
OLDNEW
« no previous file with comments | « base/base.gyp ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698