【问题标题】:Reading dynamically allocated arrays into lists将动态分配的数组读入列表
【发布时间】:2009-05-26 07:17:58
【问题描述】:

目前,我一直在以编程方式从二进制数据文件中读取数据列表,如下所示:

tplR = (double*) malloc(sampleDim[0]*sizeof(double)); printf("tplR = %d\n", fread(tplR, sizeof(double), sampleDim[0], dfile));

但是,由于我想在这些列表上使用 find_if() 函数,我需要将 tplR 转换为 stl 中的列表类型。就一般的 C++ 编程实践而言,只有当我真的需要时才将 tplR 变成一个列表通常是一种好习惯吗?

如果我确实创建了另一个成员变量,例如 tplRList,那么将所有 sampleDim[0] 个双精度条目从 tplR 推入 tplRList 的最简单方法是什么?一个一个推,直到增量计数器等于sampleDim[0]?

提前致谢。

【问题讨论】:

    标签: c++


    【解决方案1】:

    您可以像这样将 find_if 与数组一起使用:

    bool equals(int p)
    {
        return p == 9;
    }
    
    
    int main(int argc,char *argv[])
    {
        int a[10];
    
        for(int i = 0; i < 10; ++i)
        {
            a[i] = i;
        }
    
        int* p = std::find_if(a, a+10, equals);
        cout<<*p;
    
        return 0;
    }   
    

    【讨论】:

    • 如果我还需要 p 与 a 的相对位置作为指示怎么办?最简单的索引方法是否涉及 p-&a[0] 以找到相对于 &a[0] 的位置?
    【解决方案2】:

    你的假设是错误的。 std::find_if() 只需要一个迭代器,不一定是 STL 迭代器。碰巧,double* 同时支持 * 和 ++,所以它也是一个迭代器。

    【讨论】:

    • 你有使用指针作为迭代器的例子吗?我无法找到搜索词以正确查找示例。谢谢。
    【解决方案3】:

    bool checkValue(double val); std::find_if(tplR, tplR + sampleDim[0], checkValue);

    【讨论】:

      【解决方案4】:
      #include <boost/lambda/lambda.hpp\>
      
      using namespace boost::lambda;
      
      static const double whateverValueYouWant(12.);
      
      double *const tplR = (double*) malloc(sampleDim[0]*sizeof(double));
      const size_t actualItemsRead = fread(tplR, sizeof(double), sampleDim[0], dfile);
      printf("tplR = %d\n", actualItemsRead );
      
      const double *begin = tplR;
      const double *const end = tplR + actualItemsRead;
      const double *const foundItem = std::find_if( begin, end, _1== whateverValueYouWant);
      
      if( foundItem!=end )
      {
           //value found
      }
      else
      {
          //no such value
      }
      

      【讨论】:

        猜你喜欢
        • 2013-10-06
        • 2021-12-16
        • 2015-06-14
        • 1970-01-01
        • 1970-01-01
        • 2016-11-22
        • 2020-01-22
        • 2016-06-26
        • 2011-06-15
        相关资源
        最近更新 更多