Le 05/12/10 20:09, Tama Ma a écrit :
Dear Rcpp developers,

May I kindly enquire on the wrapping of a portion of a container into an
R numeric array by Rcpp::wrap?

For example, I wish to have:


template <class size_type, class element_type>
Rcpp::NumericVector
convert
(element_type*obj
,size_type*n
)
{
Rcpp::NumericVectorRvec;
Rvec.reserve(n);
std::copy( *obj , *(obj+n), std::back_inserter(Rvec));

return Rvec;
}


May I know how I can do this?

Thank you very much.

Best regards,
Tama Ma

Hello Tama,

The Vector template already has range based constructors. For example:


require( inline )
require( Rcpp )

morpheus <- cxxfunction( , '
        std::vector<double> x( 10 ) ;
        for( int i=0; i<10; i++) x[i] = sqrt( i ) ;

        NumericVector out( x.begin(), x.end() ) ;
        return out ;

', plugin = "Rcpp" )
morpheus()


Now, if you wanted your template to come up with what Vector to use you could do that sort of code by taking advantage of some of the traits we have in Rcpp :

trinity <- cxxfunction( , '
    std::vector<double> x( 10 ) ;
        for( int i=0; i<10; i++) x[i] = sqrt( i ) ;
        return convert( &x[0], x.size() )  ;

', includes = '

    template <typename elem_type, typename size_type>
    Vector< traits::r_sexptype_traits<elem_type>::rtype >
    convert( elem_type* start, size_type size ){
typedef Vector< traits::r_sexptype_traits<elem_type>::rtype > VECTOR ;
        return VECTOR( start, start + size ) ;
    }

', plugin = "Rcpp")
trinity()


Or if you know a little bit about the containers you want to convert, for example you know they have a nested value_type type, you can use something like this:

neo <- cxxfunction( , '

    std::vector<double> x( 10 ) ;
        for( int i=0; i<10; i++) x[i] = sqrt( i ) ;
        return convert(x)  ;

', includes = '

    template <typename T>
    Vector< traits::r_sexptype_traits< typename T::value_type >::rtype >
    convert( const T& x ){
typedef Vector< traits::r_sexptype_traits< typename T::value_type >::rtype > VECTOR ;
        return VECTOR( x.begin(), x.end() ) ;
    }
', plugin = "Rcpp" )
neo()


Romain


--
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://bit.ly/gpCSpH : Evolution of Rcpp code size
|- http://bit.ly/hovakS : RcppGSL initial release
`- http://bit.ly/iaxTdO : parser 0.0-12


_______________________________________________
Rcpp-devel mailing list
[email protected]
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Reply via email to