简体   繁体   中英

Division of elements in vector in c++

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 ie 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!!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM