vectorの指定したiteratorの要素番号を取得する

これも良く忘れるのでメモん。例えば最大の要素自体はmax_elementで取得できるんだけど、それのindex番号が欲しい時の書き方。iteratorの初めとのdistanceを取ればよい。別に最大要素のiteratorじゃなくても良くて適当なiteratorとのdistanceしてやればいい。

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main()
{	
    std::vector<int> x;
    x.push_back(3);
    x.push_back(8);
    x.push_back(1);
    x.push_back(2);

    std::vector<int>::iterator iter = std::max_element(x.begin(), x.end());
    size_t index = std::distance(x.begin(), iter);
    std::cout << "max element is " << x[index] << std::endl;
    return 0;   
}

実行結果

max element is 8

STL vectorをRcpp::NumericMatrixのある列(行)に代入したい

生のstl vectorをNumericMatrixに突っ込もうとすると怒られた、一方、一旦Rcpp::NumericVectorを経由させたらイケた。
以下、サンプル。行・列ごとの代入もラクラクで便利。

library(Rcpp)
library(inline)
src <- '
  std::vector<int> x(2,111);
  NumericMatrix xx(2, 5);
  xx(_,1) = NumericVector(x.begin(), x.end());
  return Rcpp::DataFrame::create(
  Rcpp::Named("id") = x,
  Rcpp::Named("vals") = xx
  );
'
f <- cxxfunction(,src,plugin="Rcpp")
f()

実行結果は↓。ちゃんと代入されている。

> f()
   id vals.1 vals.2 vals.3 vals.4 vals.5
1 111      0    111      0      0      0
2 111      0    111      0      0      0

Rcpp+inlineのインストールは