STL:在没有输出的情况下处理两个集合
STL: Processing two collections without an output
如果希望将两个集合的元素处理成第三个集合,可以使用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
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- STL:在没有输出的情况下处理两个集合
- 如何获得两个 std::unordered_map 的集合交集?
- 是同一集合上的两个不同的迭代器
- 使用 STL 算法查找集合中的前两个不相邻元素
- C++ 创建指向两个相关矢量集合中的对象的指针集合
- 将元素存储在具有两个可能索引的集合中
- 比较两个无序集合的相等性有多昂贵
- 在C++中,如何最好地解耦两个必须维护彼此引用集合的类
- 查找两个集合之间的邻近匹配对
- 如何在c++中计算两个STL集合的交集的大小
- 一个集合是否可能包含指向同一对象的两个共享指针?
- 如何找到两个集合的交集
- 在c++中,两个线程/对象在一个对象集合中可以安全地做什么?