[英]Adding vectors of doubles of differing sizes in C++
我有許多不同大小的矢量容器,每個容器都包含雙打。 我想添加每個向量的元素來創建一個雙向量向量。 這個簡單的例子將舉例說明我所說的:
考慮兩個向量A,其中三個元素為3.0 2.0 1.0,B為兩個元素2.0 1.0。 我想添加從最后一個元素開始並向后工作的兩個向量。 這將為數組C提供條目3.0 4.0 2.0。
這樣做最優雅/最有效的方法是什么?
謝謝!
嘗試使用迭代器:
#include <vector>
void add(
std::vector<double>& result,
const std::vector<double>& a,
const std::vector<double>& b)
{
std::vector<double>::const_reverse_iterator sit;
std::vector<double>::const_reverse_iterator send;
// copy the larger vector
if (a.size() > b.size() ) {
result = a;
sit = b.rbegin();
send = b.rend();
}
else {
result = b;
sit = a.rbegin();
send = a.rend();
}
// add the smaller one, starting from the back
for (std::vector<double>::reverse_iterator it = result.rbegin();
sit != send;
++it, ++sit)
{
*it += *sit;
}
}
一旦你知道你有一個比另一個更大的矢量
std::vector<double> new_vector = bigger_vector; // Copy the largest
std::transform(smaller_vector.rbegin(), smaller_vector.rend(), // iterate over the complete smaller vector
bigger_vector.rbegin(), // 2nd input is the corresponding entries of the larger vector
new_vector.rbegin(), // Output is the new vector
std::plus<double>()); // Add em
這很好,因為您不必執行任何循環縮進,並且可以在任何支持反向迭代器的序列容器上運行。
將較大的向量復制到C中,然后將(+ =)較小的元素添加到C的關聯元素中。
像這樣的東西:
std::vector<double> add(const std::vector<double>& a,
const std::vector<double>& b)
{
std::vector<double> c( (a.size() > b.size()) ? a : b );
const std::vector<double>& aux = (a.size() > b.size() ? b : a);
size_t diff = c.size() - aux.size();
for (size_t i = diff; i < c.size(); ++i)
c[i] += aux[i-diff];
return c;
}
編輯根據下面的注釋反對使用[] vs迭代器。
就個人而言,我發現迭代器對於這樣的事情過於冗長,但如果您更喜歡它們,那么您可以嘗試類似以下內容:
std::vector<double> add(const std::vector<double>& a,
const std::vector<double>& b)
{
std::vector<double> c( (a.size() > b.size()) ? a : b);
std::vector<double>::reverse_iterator c_i;
const std::vector<double>& aux = (a.size() > b.size()) ? b : a;
std::vector<double>::const_reverse_iterator aux_i;
for (c_i=c.rbegin(), aux_i=aux.rbegin(); aux_i!=aux.rend(); ++c_i, ++aux_i)
*c_i += *aux_i;
return c;
}
我沒有測試或編譯其中任何一個,但我認為你明白了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.