STL:在没有输出的情况下处理两个集合

STL: Processing two collections without an output

本文关键字:集合 两个 处理 情况下 输出 STL      更新时间:2023-10-16

如果希望将两个集合的元素处理成第三个集合,可以使用STL变换算法:

// elements of x,y are multiplied, result is in r
std::transform(x.begin(),x.end(), w.begin(), back_inserter(r), [](int _x,int _w){return _x*_w;});

如果只需要 r 元素的总和怎么办?在以下解决方案中,r 的创建是多余的:

int xwSum = 0;
std::transform(x.begin(),x.end(), w.begin(), back_inserter(r), [&xwSum](int _x,int _w){xwSum+=_x*_w; return 0;});

一定有更好的解决方案,有什么想法吗?

你可以使用std::inner_product,它完全符合你的要求:

int res = std::inner_product(x.begin(), x.end(), w.begin(), 0);  

可运行版本:https://ideone.com/zXcO2y