[英]How to multiply a vector and scalar in C++?
我想將向量與標量相乘。 這個向量是使用我的這個問題的公認答案創建的,即:
std::vector<int> n(N + 1);
std::iota(begin(n), end(n), 0);
我想將這個向量n
與一個名為npi
的標量(特別是 double 類型,如果它在這里相關的話) 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;}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.