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

时间:2016-12-08 02:43:49

标签: c++ vector

我想用矢量乘以一个标量。该向量是使用我的this question的接受答案创建的,即:

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

我希望将这个向量n乘以一个标量(特别是类型为double,如果它在这里是相关的),称为npi

我在这里看过this answer上一个问题,但并没有那么有用。我尝试实现它的方式是添加:

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 1}}矢量)。

修改

如果它会安抚那些投票结束这个问题的人,那么这是我的完整计划:

#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;
  }
}

4 个答案:

答案 0 :(得分:2)

您需要将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

答案 1 :(得分:2)

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

auto npi = n;

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

如果npi应为vector<double>(问题中不明确),请将第一行替换为:

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

答案 2 :(得分:1)

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

std::vector<double> v;
v.reserve(n.size());

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

答案 3 :(得分:0)

您可以在 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;}