tags:

views:

82

answers:

4

Currently, I have been reading lists of data from a binary data file programmatically as follows:

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

However, as I want to use find_if() function on those lists, I would need to get tplR into a list type in stl. In terms of general C++ programming practice, is it usually good practice to make tplR into a list only when I really have to?

If I do make another member variable, for example, tplRList, what would be the easiest way of pushing all sampleDim[0] number of double precision entries into tplRList from tplR? Pushing them one by one until the incremental counter is equal to sampleDim[0]?

Thanks in advance.

+1  A: 

You're mistaken in your assumptions. std::find_if() merely requires an iterator, not necessarily an STL iterator. As it happens, double* supports both * and ++, so it too is an iterator.

MSalters
Do you have any examples of using a pointer as an iterator? I'm having trouble finding search terms to look up examples properly. Thanks.
stanigator
+5  A: 

You can use find_if with the 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;
}
Naveen
+1 for beating me to it :)
Magnus Skog
stanigator
Yes, p-a will be the index.
Naveen
A: 

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

Modicom
A: 
#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
}
TimW