Reputation: 53
I am using the gnu scientific library (GSL).
Say I have a gsl_vector
like this:
7 0 -6 5 8 0 10 -2
That's a vector containing positive numbers, negative numbers, and zeros as elements.
I want to count the number of non-zero elements or zero elements in this gsl_vector
.
I know there is a function called count_if
for a C++ Vector. But I search through the gsl_vector.h
and gsl_blas.h
, there is no function equal to that.
I can go though all the elements by assessing them though gsl_vector_get()
and then ask the if question.
int counter = 0;
for(int i = 0;i<length_of_the_gsl_vector;++i){
if(fabs(gsl_vector_get(y,i))<0.5) ++counter;
}
return counter;
But I have been wondering for almost a day whether there is such a function already in GSL that is much more efficient.
Or maybe there is a count_if
function for gsl_array
?
Upvotes: 4
Views: 574
Reputation: 17642
You can get hold of the data pointer by using gsl_vector_ptr
, then use std::count_if
on pointers:
struct Predicate{
inline bool operator()(double x) const {
return fabs(x) < 0.5 ;
}
} ;
int res = std::count_if(
gsl_vector_ptr(y,0), gsl_vector_ptr(y,0) + size,
Predicate()
) ;
Upvotes: 2