Home > Software engineering >  save result of for_each algorithm inside a vector
save result of for_each algorithm inside a vector

Time:10-13

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

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

CodePudding user response:

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));
  • Related