Below I have a code snippet that encapsulates an issue I am having.
What I am trying to do would be trivial in R, but is much more difficult in Rcpp. I am just trying aggregate values according to their respective keys. In this example, I am just trying to get the sum of the values that correspond with the first key. I have done something very similar in C++, but for some reason, the Rcpp port is giving me issues.
Also, note that the code provided is only meant to represent an issue I am having with something much larger. So I understand that attempting to implement this in Rcpp alone is not a good use of time.
#include <Rcpp.h>
using namespace Rcpp;
using namespace std;
// [[Rcpp::export]]
int mmap(List x) {
std::multimap<int, int> out;
for(int i = 0; i < x.size(); ++i) {
int key_temp = as<List>(as<List>(x[i]))[0];
int value_temp = as<List>(as<List>(x[i]))[1];
out.insert(make_pair(key_temp, value_temp));
}
pair<multimap<int, int>::iterator, multimap<int, int>::iterator> range = out.equal_range(1);
int total = accumulate(range.first, range.second, 0);
return total;
}
/*
xList <- list()
xList[[1]] <- list()
xList[[1]][1] <- 1
xList[[1]][2] <- 1
xList[[2]] <- list()
xList[[2]][1] <- 1
xList[[2]][2] <- 2
xList[[3]] <- list()
xList[[3]][1] <- 2
xList[[3]][2] <- 2
xList[[4]] <- list()
xList[[4]][1] <- 1
xList[[4]][2] <- 2
mmap(xList)
*/
One of the first error messages you get is instructive:
The compiler does not know how to add your starting value (an
int
) with the new value from the iterator (apair
representing the key-value-pair). Fortunatelystd::accumulate
takes an optional argument with a function that is to be applied. Using C++11 we can use a simple lambda function:Result: