Copy the larger vector into C and then add (+=) the elements of the smaller against the associated elements of C.
Somthing like:
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;
}
Edit Based on comment below objecting to use of [] vs iterators.
Personally I find iterators to be excessively verbose for something like this, but if you prefer them, then you could try somehting like the following:
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;
}
I didn't test or compile either of these, but I think you get the idea.