什么是std :: find这个错误的优雅解决方案?

问题描述:

我有一个类,它包含一个在编译时未知的数组。该数组在构造函数中初始化。然后,我有检查的其他功能,如果一个元素是数组中:什么是std :: find这个错误的优雅解决方案?

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 */ 
    } 
}; 

我得到了以下错误:

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

出了什么问题上面这段代码?我知道我不能在指针中使用std :: find,但是我的数组是一个数组,而不是一个腐朽的指针。

我跟着this的例子。我还包括算法头。我究竟做错了什么?

我在C++ 11中编译我的代码。

编辑:我现在明白了。但我怎样才能以优雅的方式做我想做的事?

  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?
+6

'INT标签[];'你不能有空数组。 –

+0

@πάνταῥεῖ,我的数组不是空的,它还没有被初始化。编译器不会抱怨。你能否建议我想要实现的替代解决方案? – user2738748

+0

你是从哪里初始化它的? –

int tab[]; 

标准不允许空数组,但一些编译器做的扩展。这并不是合法的。

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

事实并非如此,你仍然可以使用std::finds是你的标签数组的大小)。

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?

使用std::vector<int>,然后调用resize()