Home > other >  Is there a way to use an array passed as parameter on std::begin or std::end?
Is there a way to use an array passed as parameter on std::begin or std::end?

Time:11-07

I keep getting a compilation error if I use an array passed as parameter to a method on std::begin or std::end such as this:

#include <iostream>
#include <algorithm>

using namespace std;

class Test
{
public:
    static bool exists(int ints[], int size, int k)
    {
        if (std::find(std::begin(ints), std::end(ints), k) != std::end(ints)) {
            return true;
        }
        return false;
    }
};

I tried casting it to &int[0] but it will still not compile.

CodePudding user response:

The parameter ints is not an array, so you aren't passing an array into std::begin / std::end in the example. A function parameter is never an array in C . When you declare a function array to be an array such as in your example, that parameter is adjusted to be a pointer to the element of such array. In your case, the type of the parameter ints has been adjusted to be a pointer to int i.e. int*, and you cannot pass a pointer into std::begin / std::end, as the error message surely explains.

You have passed the size as another parameter, so you could instead use:

std::find(ints, ints   size, k)

A more modern API design is to wrap the pointer and the size into a single class. The C 20 standard library comes with such class template: std::span. It also has convenient range algorithms that are quite convenient:

static bool exists(std::span<const int> ints, int k)
{
    if (std::ranges::find(ints, k) != std::end(ints)) {

Even moreso, C 20 standard library has a function template that makes your function unnecessary:

std::ranges::contains(some_array, k);

CodePudding user response:

Here is a working example.

#include <iostream>
#include <vector>
bool exists(int x[], const  int size, const int k)
{
    std::vector<int> v(x, x   size);
    if (std::find( v.begin(), v.end(), k) != v.end()) {
        return true;
    }
    return false;
}
int main()
{
    int const sz = 10;
    int arrayi[sz] = { 1, 2, 3,4 ,5 ,6 ,7 , 8, 9, 0 };
    if (exists(arrayi, sz, 4))
        std::cout << "exist" << std::endl;
    else
        std::cout << "it does not" << std::endl;
}

CodePudding user response:

Use std::span.

try this:

#include <algorithm>
#include <iostream>
#include <span>

bool exists(std::span<int> span, int needle) {
  return std::find(span.begin(), span.end(), needle) != span.end();
}

int main() {
  int arr[] = {0, 1, 2, 3, 4};
  bool ok = exists(arr, 3);
  if (ok) {
    std::cout << "ok" << '\n';
  } else {
    std::cout << "not ok" << '\n';
  }

  return 0;
}

  •  Tags:  
  • c
  • Related