Reading dynamically allocated arrays into lists

I am currently reading lists of data from a binary data file programmatically like this:

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

However, since I want to use the function find_if()

on these lists, I will need to get the tplR as a list in stl. As far as general programming practice in C ++ is concerned, is it usually good practice to make tplR into a list only when I really need to?

If I make another member variable like tplRList, what's the simplest way to push all number of double precision sampleDim [0] instances into tplRList from tplR? Pressing them one by one until the incremental counter equals sampleDim [0]?

Thanks in advance.

0


a source to share


4 answers


You can use find_if with an array like this:



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

      

+5


a source


You are wrong in your assumptions. std::find_if()

it just needs an iterator, not necessarily an STL iterator. As it happens, it double*

supports both * and ++, so it is an iterator too.



+1


a source


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

0


a source


#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
}

      

0


a source







All Articles