如何在C++中乘以向量和标量?

How to multiply a vector and scalar in C++?

本文关键字:向量 标量 C++      更新时间:2023-10-16

我想用标量乘以一个向量。这个向量是使用我的这个问题的公认答案创建的,即:

std::vector<int> n(N + 1);
std::iota(begin(n), end(n), 0);

我想将这个向量n乘以一个名为npi的标量(特别是双精度类型,如果它在这里相关)。

我在这里看到了对上一个问题的回答,但它并没有那么有帮助。我尝试实现它的方式是添加:

std::transform(n.begin(), n.end(), n.begin(),
std::bind1st(std::multiplies<T>(),pin));

到我的C++程序。这返回了编译错误:

error: ‘T’ was not declared in this scope
std::bind1st(std::multiplies<T>(),pin));

我想调用通过将这个向量与标量npi相乘来创建的向量,所以请不要给我调用这个新向量的代码n(即覆盖我现有的n向量)。

编辑:

如果它能安抚任何投票关闭这个问题的人,这是我的完整计划:

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>
#include <utility>
#include <unistd.h>
#include <algorithm>
#include <numeric>
/*#include <armadillo>*/
using namespace std;
/*using namespace arma;*/
double N  = 1000.0;
double x0 = 0;
double x1 = 100;
double pin = M_PI / double(N);
int main() {
std::vector<int> n(N + 1);
std::iota(begin(n), end(n), 0);
std::transform(n.begin(), n.end(), n.begin(),
std::bind1st(std::multiplies<T>(),pin));
for(double i: n)
{
std::cout << i << 'n' << std::scientific;
}
}

对于vector<int>输出,一种方法是:

auto npi = n;
for( auto& i: npi )
i *= pin;

如果npi应该vector<double>(从问题中不清楚),则将第一行替换为:

std::vector<double> npi( n.begin(), n.end() );

您需要将T替换为向量中包含的类型,在本例中为int。但是,您可以通过在此处使用 lambda 函数来简化代码:

#include <algorithm> // for std::transform
#include <cmath>     // for M_PI
#include <iostream>  // for std::cout etc
#include <numeric>   // for std::iota
#include <vector>    // for awesome
int main() {
std::vector<int> vec1(10);
std::iota(vec1.begin(), vec1.end(), 0);
int N = 42;
std::vector<double> vec2(vec1.size()); // vec2 needs to be as big or bigger than vec1
std::transform(vec1.begin(), vec1.end(), vec2.begin(),
[N](int i) { return i * M_PI / N; });
for (auto a : vec1)
std::cout << a << " ";
std::cout << std::endl;
for (auto a : vec2)
std::cout << a << " ";
std::cout << std::endl;
}

下面是一个在线示例:http://melpon.org/wandbox/permlink/XrNxDND0steJmym8

如果我理解正确,您需要以下内容

std::vector<double> v;
v.reserve(n.size());
std::transform(n.begin(), n.end(), std::back_inserter( v ),
std::bind1st(std::multiplies<double>(), pin));

您可以在 Lambda 函数的捕获子句中传递标量,并在 lambda 函数本身内执行乘法

#include <algorithm>
#include <vector>

std::vector<int> foo; 
std::vector<int> bar;
auto npi=4.0;
std::transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), [&npi](auto& c){return c * npi;}