我是一名新手,试图在Rcpp中使用标准模板库(STL)来学习数据结构和算法实现。
我正在尝试使用Rcpp中的unordered_map实现一个非常基本的哈希表,从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
我坦率地不知道如何调试代码。请帮忙。
答案 0 :(得分:4)
()
旁边的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;
}