gpt4 book ai didi

c++ - 使用 STL 将 vector 元素乘以标量值

转载 作者:IT老高 更新时间:2023-10-28 12:35:03 26 4
gpt4 key购买 nike

您好,我想通过标量值(乘法、加法等) vector ,例如 myv1 * 3 ,我知道我可以使用 forloop 执行函数,但有没有办法做到这一点使用 STL 功能? {Algorithm.h::变换函数}之类的东西?

最佳答案

是的,使用 std::transform:

std::transform(myv1.begin(), myv1.end(), myv1.begin(),
std::bind(std::multiplies<T>(), std::placeholders::_1, 3));

在 C++17 之前,您可以使用 std::bind1st(),它在 C++11 中已被弃用。

std::transform(myv1.begin(), myv1.end(), myv1.begin(),
std::bind1st(std::multiplies<T>(), 3));

对于占位符;

#include <functional> 

关于c++ - 使用 STL 将 vector 元素乘以标量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3885095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com