Saturday, July 12, 2014

Initialize a vector of vectors in c++

You can initialize a empty vector of vectors and then use the push_back method, but this cannot be done when you want the vector to be also const and globally available, in which case its values must be set up during initialization. Here is one nice way to do it:

// [[Rcpp::export]]
void vecvec() {
 const std::vector< std::vector<int> > y {
  std::vector<int> {1, 2},
  std::vector<int> {3, 4},
  std::vector<int> {5, 6}
 };
 for(std::vector<int> i : y) {
  for(int j : i) {
   Rcout << j << "\t";
  }
  Rcout << "\n";
 }
}

Source this into R:

# R code

> Sys.setenv("PKG_CXXFLAGS"="-std=c++11")
> require(Rcpp)
> sourceCpp("main.cpp")
> vecvec()
1 2
3 4
5 6

0 comments: