Reputation: 35
I want to loop over vect, call a function on each element, perform an operation between both the results and append that to a new vector. Is there a better way to do this?
std::vector<int> vect = {{1,2},{3,4}};
std::vector<double> out(vect.size());
for (int i = 0; i < vect.size(); i++){
double v = somefunction(vect[i][0]) - somefunction(vect[i][1]);
out.push_back(v);
}
Upvotes: 2
Views: 89
Reputation: 38277
This is what std::transform
can be used for.
#include <algorithm>
std::vector<double> out(vect.size());
std::transform(vect.cbegin(), vect.cend(), out.begin(), [](const auto& inner)
{ return somefunction(inner.front()) - somefunction(inner.back()); });
This assumes that vect
is a container of size 2
with front()
and back()
member functions that do what one would expect them to do.
Upvotes: 5
Reputation: 6805
Assuming your vect
is a std::vector <std::vector <double>>
as it seems to be, you could simply write:
std::vector <double> out;
for(size_t i = 0; i < vect.size(); ++i)
{
out.push_back(someFunction(vect[i][0]) - someFunction(vect[i][1]));
}
or
std::vector <double> out;
for(auto & v : vect)
{
out.push_back(someFunction(v[0]) - someFunction(v[1]));
}
You don't have to initialize out
as you did because push_back()
will add another element at the end of what you already have added in the construction.
Note that if vect
only contains vectors of size two, you can use std::pair
instead, for example:
std::vector<std::pair<double, double>> vect;
And replace the previous loop by:
std::vector <double> out;
for(size_t i = 0; i < vect.size(); ++i)
{
out.push_back(someFunction(vect[i].first) - someFunction(vect[i].second));
}
or
std::vector <double> out;
for(auto & v : vect)
{
out.push_back(someFunction(v.first) - someFunction(v.second));
}
Upvotes: 1