1
2 // max.h: Rcpp R/C++ interface class library -- max
3 //
4 // Copyright (C) 2012 - 2018 Dirk Eddelbuettel and Romain Francois
5 //
6 // This file is part of Rcpp.
7 //
8 // Rcpp is free software: you can redistribute it and/or modify it
9 // under the terms of the GNU General Public License as published by
10 // the Free Software Foundation, either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // Rcpp is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with Rcpp. If not, see <http://www.gnu.org/licenses/>.
20
21 #ifndef Rcpp__sugar__max_h
22 #define Rcpp__sugar__max_h
23
24 namespace Rcpp{
25 namespace sugar{
26
27 template <int RTYPE, bool NA, typename T>
28 class Max {
29 public:
30 typedef typename Rcpp::traits::storage_type<RTYPE>::type STORAGE ;
31
Max(const T & obj_)32 Max( const T& obj_) : obj(obj_) {}
33
STORAGE()34 operator STORAGE() const {
35 R_xlen_t n = obj.size();
36 if (n == 0) return(static_cast<STORAGE>(R_NegInf));
37
38 STORAGE max, current ;
39 max = obj[0] ;
40 if( Rcpp::traits::is_na<RTYPE>( max ) ) return max ;
41 for( R_xlen_t i=1; i<n; i++){
42 current = obj[i] ;
43 if( Rcpp::traits::is_na<RTYPE>( current ) ) return current;
44 if( current > max ) max = current ;
45 }
46 return max ;
47 }
48
49 private:
50 const T& obj ;
51 } ;
52
53 // version for NA = false
54 template <int RTYPE, typename T>
55 class Max<RTYPE,false,T> {
56 public:
57 typedef typename Rcpp::traits::storage_type<RTYPE>::type STORAGE ;
58
Max(const T & obj_)59 Max( const T& obj_) : obj(obj_) {}
60
STORAGE()61 operator STORAGE() const {
62 R_xlen_t n = obj.size();
63 if (n == 0) return(static_cast<STORAGE>(R_NegInf));
64
65 STORAGE max, current ;
66 max = obj[0] ;
67 for( R_xlen_t i=1; i<n; i++){
68 current = obj[i] ;
69 if( current > max ) max = current ;
70 }
71 return max ;
72 }
73
74 private:
75 const T& obj ;
76 } ;
77
78
79 } // sugar
80
81 template <int RTYPE, bool NA, typename T>
max(const VectorBase<RTYPE,NA,T> & x)82 sugar::Max<RTYPE,NA,T> max( const VectorBase<RTYPE,NA,T>& x){
83 return sugar::Max<RTYPE,NA,T>(x.get_ref()) ;
84 }
85
86 } // Rcpp
87
88 #endif
89