0

I have a class which contains an array which size is unknown at compile time. The array is initialized in the constructor. Then, I have another function that checks if an element is in the array:

class myClass
{
   int tab[];
  public:
   myClass(int array[], int length)
   {  
      std::copy(array, array + length, tab)
   }
   void myFunction()
   {
      int x = 8;
      int *ptr = std::find(std::begin(tab), std::end(tab), tdc_x);
      if (ptr) /* here goes my code */
   }
};

I got the following error:

error: no matching function for call to ‘begin(int [0])’

What's wrong with the above piece of code? I know that I can't use std::find with pointers, but my array is an array, not a decayed pointer.

I followed this example. I also included the algorithm header. What am I doing wrong?

I compile my code in C++11.

Edit: I get it now. But how can I do what I want to do in an elegant way?

  1. If I use a pointer instead of the empty array, I won't be able to use std::find.
  2. if I give my array an arbitrary size, I won't be able to copy a bigger array. What should I do?
Community
  • 1
  • 1
user2738748
  • 1,106
  • 2
  • 19
  • 36

1 Answers1

2
int tab[];

The standard doesn't allow empty arrays, but some compilers do as an extension. That doesn't make it legit tho.

If I use a pointer instead of the empty array, I won't be able to use std::find.

Not true, you can still use std::find (s is the size of your tab array).

  int *ptr = std::find(tab, tab + s, tdc_x);

if I give my array an arbitrary size, I won't be able to copy a bigger array. What should I do?

Use a std::vector<int>, then call resize()

Jts
  • 3,447
  • 1
  • 11
  • 14