開始使用免費開始

第一個函式——再來一次

回想第 1 章的 the_answer() 函式,會固定回傳 42。這次把它改寫成 C++ 檔案。

這個檔案包含以下部分:

  1. 透過「#include」指令取得 Rcpp 的功能。
  2. using namespace 宣告,方便輸入程式碼。
  3. 函式定義。
  4. Rcpp 的 R 註解區塊,用來在 C++ 程式碼編譯後呼叫該函式。

本練習屬於課程

用 Rcpp 最佳化 R 程式碼

檢視課程

練習說明

  • 包含 Rcpp.h 標頭檔。
  • 宣告要使用 Rcpp 命名空間。
  • 讓函式回傳 42
  • 在 Rcpp 的 R 註解區塊中呼叫該函式。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

// Include the Rcpp.h header
#include <___>

// Use the Rcpp namespace
using ___ ___;

// [[Rcpp::export]]
int the_answer() {
    // Return 42
    return ___;
}

/*** R
# Call the_answer() to check you get the right result
___
*/
編輯並執行程式碼