unordered_map 在 rcpp 中使用

unordered_map use in rcpp

我是一个新手,正在尝试使用 Rcpp 中的标准模板库 (STL) 学习数据结构和算法实现。

我正在尝试在 Rcpp 中使用 unordered_map 实现一个非常基本的散列 table,从 Hadley 的 Advanced R

中得到提示

这是我想在 Rcpp 中实现的 C++ 代码(摘自 element14 blog

#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;

int main()
{
unordered_map<string, string> hashtable;
hashtable.emplace("www.element14.com", "184.51.49.225");

cout << "IP Address: " << hashtable["www.element14.com"] << endl;

return 0;

}

我的相同代码的Rcpp版本是(请忽略int main,我暂时将其命名为int hash)

// [[Rcpp::plugins(cpp11)]]
#include <Rcpp.h>
#include <unordered_map>
#include <string>


using namespace Rcpp;

//[[Rcpp::export]]
int hash_test{
std::unordered_map<std::string, std::string> hashtable;
hashtable.emplace("www.element14.com", "184.51.49.225");

Rcout << "IP Address: " << hashtable["www.element14.com"] << endl;
return 0;
}

在 运行

sourceCpp("./hash_test.cpp")

我得到以下错误(我不是 C++ 专业人士,所以请忽略任何愚蠢的错误)

hash_test.cpp:11:46: error: expected primary-expression before ‘hashtable’
 std::unordered_map<std::string, std::string> hashtable;
                                              ^
hash_test.cpp:11:46: error: expected ‘}’ before ‘hashtable’
hash_test.cpp:11:46: error: expected ‘,’ or ‘;’ before ‘hashtable’
hash_test.cpp:12:1: error: ‘hashtable’ does not name a type
 hashtable.emplace("www.element14.com", "184.51.49.225");
 ^
hash_test.cpp:14:1: error: ‘Rcout’ does not name a type
 Rcout << "IP Address: " << hashtable["www.element14.com"] << endl;
 ^
hash_test.cpp:15:1: error: expected unqualified-id before ‘return’
 return 0;
 ^
hash_test.cpp:16:1: error: expected declaration before ‘}’ token
 }
 ^
make: *** [hash_test.o] Error 1
Error in sourceCpp("./CDM_Open_Source_ME/kohls_model/hash_test.cpp") : 
  Error 1 occurred building shared library.
In addition: Warning message:
No function found for Rcpp::export attribute at hash_test.cpp:9 

坦率地说,我不知道如何调试代码。请帮忙。

hash_test 旁边确实缺少 ()

以下作品:

// [[Rcpp::plugins(cpp11)]]
#include <Rcpp.h>
#include <unordered_map>
#include <string>


// [[Rcpp::export]]
int hash_test() { // missed the ()

  std::unordered_map<std::string, std::string> hashtable;

  hashtable.emplace("www.element14.com",
                    "184.51.49.225");

  Rcpp::Rcout << "IP Address: " << hashtable["www.element14.com"] << std::endl;
  return 0;
}