Reputation: 89
I have vector in c++ something like std::vector<double> v = {10.0, 5.0, 2.0}
. I want to divide the all the elements of the vector sequentially i.e 10/5.0 =2.0 and then 2.0/2.0 which should be 1. So, the final answer is the division of all elements of the vector. Is there any way to this efficiently using some STL function or algorithm. I do not want to use for
loop. Thanks for the help!!
Upvotes: 0
Views: 4943
Reputation: 13434
As @Algirdas Preidžius mentioned in a comment (I started to write my answer before it popped), you probably just missed the fact that the algorithm should start with the first number and not divide by it. This should be what you're expecting:
int main()
{
std::vector<double> vec = {10, 5, 2};
std::cout << std::accumulate(vec.cbegin() + 1, vec.cend(),
vec[0], std::divides<>());
}
Notice the + 1
after vec.cbegin()
and vec[0]
as the starting value
Upvotes: 4