c++ - 来自 std::find 的此错误的优雅解决方案是什么?

标签 c++ arrays c++11 std c++-standard-library

我有一个类,其中包含一个在编译时大小未知的数组。数组在构造函数中初始化。然后,我有另一个函数检查一个元素是否在数组中:

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 编译我的代码。

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

  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?

最佳答案

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/

相关文章:

php - 海量 PHP 数组与 MySQL 数据库?

c++ - 为什么我们必须为带有默认参数的模板类指定<>?

c++ - 当 header 中指定文本/纯文本时,eBay API 返回 JSON

c++ - 运行时绑定(bind)和模板实例化

php - 多维数组转json

php - 传递 Javascript 数组 -> PHP

c++ - 避免构造函数中 const 引用和 rvalue 引用的指数增长

c++ - 如何确保一些代码被优化掉?

c++ - 获取已发送邮件的附件数量

c++ - C++空缺数字崩溃