mercredi 24 janvier 2018

Define custom iterator that calls function to passed element

I am often writing code like the following (here int and double are just example, types are usually pointers)

std::vector<int> va {1 ,2, 3};
std::vector<double> vb;

bool valid(int i) { return i % 2 == 0;}

for(auto a : va)
   if (valid(a))
      vb.push_back(static_cast<double>(a));

Since we don't have transform_if I would like to know if there is a way to do this by definining some special iterator:

template<typename T>
struct inserterStaticCast
{
    // not sure what to put here...
}

Then I could write code like

std::vector<double> vc(a.size());
std::copy_if(a.begin(), a.end(), inserterStaticCast<double>(vc), &valid);

I would also be interested in the backInserterStaticCast version.

Is this possible in C++11?

Thank you

Aucun commentaire:

Enregistrer un commentaire