Home > Net >  Count square numbers in array using count function
Count square numbers in array using count function

Time:04-04

I need to count how many numbers are perfect squares in array of integer values, using a function from the algorithm library.

I have chosen the std::count() function to do that:

#include <algorithm>
#include <iostream>
#include <math.h>
bool is_square_number(int x) {
  if (x >= 0) {
    long long sr = sqrt(x);
    return (sr * sr == x);
  }
  return false;
}
int count_square_numbers(int *arr, int *arr2) {
  int number = 0;
  while (arr < arr2) {
    if (is_square_number(*arr))
      number  ;
    arr  ;
  }
  return number;
}
int main() {
  int n=9,arr[9]={1,2,3,4,5,6,7,8,9};
  std::cout << count_square_numbers(arr, arr   n);
  std::cout<<std::count(arr,arr n,count_square_numbers);
  return 0;
}

When I use std::cout << count_square_numbers(arr, arr n), the program prints 3 as result (correctly); but, when I try to use it in the function, std::count, I cannot compile my code.

Could you explain what is the problem here and how could I use the std::count function for this?

Error I get:

ISO C forbids comparison between pointer and integer [-fpermissive]

CodePudding user response:

First, you are confusing the std::count function – which just counts how many values in the container/range are equal to the last parameter (which is a value, not a function)1 – with the std::count_if function (which counts how many values satisfy the predicate, specified as the last parameter and should be a function or lambda taking an element from the range as an argument and returning a bool value).

Then, even when using std::count_if, you just pass it the actual test function (in your case, is_square_number, which fulfils the requirements for the unary predicate), rather than the full, loop-counter function:

#include <algorithm>
#include <iostream>
#include <math.h>

bool is_square_number(int x)
{
    if (x >= 0) {
        long long sr = sqrt(x);
        return (sr * sr == x);
    }
    return false;
}

int count_square_numbers(int* arr, int* arr2)
{
    int number = 0;
    while (arr < arr2) {
        if (is_square_number(*arr))
            number  ;
        arr  ;
    }
    return number;
}

int main()
{
    int n = 9, arr[9] = { 1,2,3,4,5,6,7,8,9 };
    std::cout << count_square_numbers(arr, arr   n) << "\n";
    std::cout << std::count_if(arr, arr   n, is_square_number) << "\n";
    return 0;
}

See: cppreference for fuller details.


1 When a function is passed as an argument to another function (as in your code), it is converted to a pointer to the function – hence the error message: The std::count function is attempting to compare values from the integer array with the function pointer.

  • Related