如何在C++中乘以向量和标量?
How to multiply a vector and scalar in C++?
我想用标量乘以一个向量。这个向量是使用我的这个问题的公认答案创建的,即:
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;}
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 为 2D 向量类创建标量乘法运算符
- CUDA:复杂标量 *双稀疏矩阵 *双向量
- 如何在C++中乘以向量和标量?
- 基于输入数据创建 STL 向量 - 标量或复杂类型
- 用程序求向量等式中的标量
- C++返回一个向量(将 int 转换为非标量类型)
- 特征:从向量中减去标量
- 我应该如何使用表达式模板来实现数学向量类的标量乘法
- 以C++为单位将向量乘以标量
- 2个向量的标量乘Eigen
- STL向量除以标量操作符重载
- 如何使用+=运算符实现标量和向量相加
- 用标量有效地乘大复数向量