1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
long long add( const std::vector<int>& first, const std::vector<int>& second )
{
long long result = 0 ;
const auto min_size = std::min( first.size(), second.size() ) ;
for( std::size_t i = 0 ; i < min_size ; ++i ) result += (long long)first[i] * second[i] ;
return result ;
}
long long add_recursive( const std::vector<int>& first, const std::vector<int>& second, std::size_t from_pos = 0 )
{
if( from_pos >= std::min( first.size(), second.size() ) ) return 0 ;
else return (long long)first[from_pos] * second[from_pos] + add_recursive( first, second, from_pos+1 ) ;
}
long long add_smart( const std::vector<int>& first, const std::vector<int>& second )
{
const auto min_size = std::min( first.size(), second.size() ) ;
// https://en.cppreference.com/w/cpp/algorithm/inner_product
return std::inner_product( first.begin(), first.begin()+min_size, second.begin(), 0LL ) ;
}
int main()
{
const std::vector<int> first { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;
const std::vector<int> second { 2, 4, 6, 8, 10 } ;
std::cout << add( first, second ) << '\n'
<< add_recursive( first, second ) << '\n'
<< add_smart( first, second ) << '\n' ;
}
|