如何在 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;
  }
}

原文由 Josh Pinto 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 797
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

原文由 Jack Deeth 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

 auto npi = n;

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

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

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

原文由 M.M 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题