Sunday, July 20, 2014

Insert array data into std::vector in c++

The begin() and end() function are very handy here!


#include 
#include 
#include "gencodes.h"

#include "RcppArmadillo.h"

// via the depends attribute we tell Rcpp to create hooks for
// RcppArmadillo so that the build process will know what to do
//
// [[Rcpp::depends(RcppArmadillo)]]


using namespace Rcpp;
using namespace std;

// [[Rcpp::export]]
void test_insert_array() {
 std::vector myvec;
 myvec.reserve(4 * sizeof(int));
 int a1[2] = {1, 2};
 int a2[2] = {3, 4};
 myvec.insert(myvec.end(), begin(a1), end(a1));
 myvec.insert(myvec.end(), begin(a2), end(a2));
 for(int i : myvec) {
  Rcout << i << "\n";
 }
}

Note if you initialize myvec with length 4 instead of using reserve method, you will find the 4 numbers appended to a vector $(0, 0, 0, 0)$, and the end result would be $(0, 0, 0, 0, 1,2,3,4)$.


// [[Rcpp::export]]
void test_insert_array() {
 std::vector myvec(4);
 // myvec.reserve(4 * sizeof(int));
 int a1[2] = {1, 2};
 int a2[2] = {3, 4};
 myvec.insert(myvec.end(), begin(a1), end(a1));
 myvec.insert(myvec.end(), begin(a2), end(a2));
 for(int i : myvec) {
  Rcout << i << "\n";
 }
}

0 comments: