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

Unified 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 side-by-side diff with in-line comments
Download patch
« no previous file with comments | « base/base.gyp ('k') | no next file » | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: base/cpp101/fibonacci.cc
diff --git a/base/cpp101/fibonacci.cc b/base/cpp101/fibonacci.cc
new file mode 100644
index 0000000000000000000000000000000000000000..ea882b3bb809dbd7baa333ba1598651d8bca69cb
--- /dev/null
+++ b/base/cpp101/fibonacci.cc
@@ -0,0 +1,56 @@
+// Copyright 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <stdio.h>
+
+#include "base/bind.h"
+#include "base/bind_helpers.h"
+#include "base/callback.h"
+#include "base/strings/string_number_conversions.h"
+
+namespace {
+
+struct FibonacciState {
+ FibonacciState() : i(0), j(1) {}
+
+ int i, j;
+};
+
+int ComputeNextFibonacciNumber(FibonacciState* state) {
+ int next = state->i + state->j;
+ state->i = state->j;
+ state->j = next;
+ return state->i;
+}
+
+base::Callback<int()> MakeFibonacciClosure() {
+ scoped_ptr<FibonacciState> state(new FibonacciState);
+ return base::Bind(&ComputeNextFibonacciNumber, base::Owned(state.release()));
+}
+
+} // namespace
+
+int main(int argc, char* argv[]) {
+ if (argc <= 1) {
+ printf("%s: missing operand\n", argv[0]);
+ return -1;
+ }
+
+ int n = 0;
+ if (!base::StringToInt(argv[1], &n) || n < 0) {
+ printf("%s: invalid n `%s'\n", argv[0], argv[1]);
+ return -1;
+ }
+
+ base::Callback<int()> fibonacci_closure1 = MakeFibonacciClosure();
+ base::Callback<int()> fibonacci_closure2 = MakeFibonacciClosure();
+ for (int i = 0; i < n; ++i) {
+ int j = fibonacci_closure1.Run();
+ int k = fibonacci_closure2.Run();
+ DCHECK_EQ(j, k);
+ printf("F_%d = %d\n", i, j);
+ }
+
+ return 0;
+}
« 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