作者:520sweet跃_322 | 来源:互联网 | 2022-12-06 19:22
对于像NA
or 这样的特殊值NaN
,boost::unordered_map
每次使用时都会创建一个新密钥insert
.
// [[Rcpp::depends(BH)]]
#include
#include
using namespace Rcpp;
// [[Rcpp::export]]
void test_unordered_map(NumericVector vec) {
boost::unordered_map mymap;
int n = vec.size();
for (int i = 0; i ::iterator it = mymap.begin(), end = mymap.end();
while (it != end) {
Rcout <first <<"\t";
it++;
}
Rcout <
结果:
> x <- c(sample(10, 100, TRUE), rep(NA, 5), NaN)
> test_unordered_map(x)
nan nan nan nan nan nan 4 10 9 5 7 6 2 3 1 8
如何只创建一个密钥NA
和一个密钥NaN
?
1> Ralf Stubner..:
bartop使用自定义comperator的想法很好,虽然特定的形式对我不起作用.所以我用Boost的文档作为起点.结合R的合适功能我得到:
// [[Rcpp::depends(BH)]]
#include
#include
using namespace Rcpp;
struct R_equal_to : std::binary_function {
bool operator()(double x, double y) const {
return (R_IsNA(x) && R_IsNA(y)) ||
(R_IsNaN(x) && R_IsNaN(y)) ||
(x == y);
}
};
// [[Rcpp::export]]
void test_unordered_map(NumericVector vec) {
boost::unordered_map, R_equal_to> mymap;
int n = vec.size();
for (int i = 0; i ::iterator it = mymap.begin(), end = mymap.end();
while (it != end) {
Rcout <first <<"\t";
it++;
}
Rcout <
结果:
> x <- c(sample(10, 100, TRUE), rep(NA, 5), NaN) + 0
> test_unordered_map(x)
7 2 nan nan 4 6 9 5 10 8 1 3
如所希望的,NA
并且NaN
被插入一次.但是,在这个输出中无法区分它们,因为R NA
只是IEEE NaN的一种特殊形式.
2> bartop..:
根据IEEE标准,NaN值与==
任何事物相比总是假的.所以,你不能这样做.您可以提供自己的比较器来unordered_map
使用此std::isnan
功能.
auto comparator = [](auto val1, auto val2) {
return std::isnan(val1) && std::isnan(val2) || val1 == val2;
}
boost::unordered_map, decltype(comparator)> mymap(comparator);