Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

save result of for_each algorithm inside a vector

I have a functor and the overloaded operator() of it returns a double. In an easy way I can write:

int main(){
    auto f=[](double  t){return 1.0/(pow(7.0*t,2.0)+1.0);};
    std::vector<double> nodes(n);
    bestpolchevnod(f,nodes); //calculate nodes = f_i(cheby_point(i))
    ChebyPoly c_p = ChebyPoly(nodes);//call the constructor with the calculated nodes
    std::cout << c_p(0.6) << std::endl; //evaluate at c_p(0.6) as an approx of f(0.6)
};

Now it is possible to go through a set of values by using for_each() like:

std::vector<double> xpoints={0.4,0.5,0.6,0.7};
std::for_each(xpoints.begin(), xpoints.end(), ChebyPoly(nodes));

Is there a sharp/short way to save the calculated values of this algorithm directly for example in a vector? I know there are ways to do it otherwise. But I wonder if there is something similar like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

std::vector<double> resvec(xpoints.size());
resvec.push_back(std::for_each(xpoints.begin(), xpoints.end(), ChebyPoly(nodes))); // wrong

>Solution :

std::for_each is the wrong algorithm, you want std::transform

std::vector<double> resvec(xpoints.size());
std::transform(xpoints.begin(), xpoints.end(), resvec.begin(), ChebyPoly(nodes));

Or without zero-initialising the elements of resvec

std::vector<double> resvec;
resvec.reserve(xpoints.size());
std::transform(xpoints.begin(), xpoints.end(), std::back_inserter(resvec), ChebyPoly(nodes));

Or without allocating a result, instead having a lazy view

auto result = xpoints | std::ranges::views::transform(ChebyPoly(nodes));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading