我有一个类,其中包含一个在编译时大小未知的数组。数组在构造函数中初始化。然后,我有另一个函数检查一个元素是否在数组中:
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例子。我还包含了 algorithm header 。我做错了什么?
我用 C++11 编译我的代码。
编辑:我现在明白了。但是我怎样才能以优雅的方式做我想做的事情呢?
- If I use a pointer instead of the empty array, I won't be able to use std::find.
- if I give my array an arbitrary size, I won't be able to copy a bigger array. What should I do?
最佳答案
int tab[];
标准不允许空数组,但一些编译器作为扩展允许。但这并不能使它合法。
If I use a pointer instead of the empty array, I won't be able to use std::find.
不对,您仍然可以使用 std::find
(s
是您的选项卡数组的大小)。
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()
关于c++ - 来自 std::find 的此错误的优雅解决方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35872699/