std::inner_product函数可以用于计算两个序列的内积。在这个函数中,我们需要传递四个参数:两个源序列的起始迭代器、一个初始值和一个二元函数对象。
以下是一个示例代码,演示了如何使用std::inner_product函数计算两个序列的内积:
#include <iostream>
#include <vector>
#include <numeric>
double calc_confi_interval(double rtt_interval_ratio) {
return 1.96 * rtt_interval_ratio / std::sqrt(2);
}
int main() {
std::vector<double> rtt_interval_ratios = {0.5, 0.6, 0.7, 0.8, 0.9};
std::vector<double> rtt_interval_weights = {0.1, 0.2, 0.3, 0.4, 0.5};
std::vector<double> rtt_interval_confidences(rtt_interval_ratios.size());
int N_intervals = 3;
std::transform(rtt_interval_ratios.begin(), rtt_interval_ratios.begin() + N_intervals,
rtt_interval_confidences.begin(), calc_confi_interval);
double res = std::inner_product(rtt_interval_confidences.begin(), rtt_interval_confidences.begin() + N_intervals,
rtt_interval_weights.begin(), 0.0);
std::cout << res << std::endl;
return 0;
}
通过使用std::inner_product函数,我们可以方便地计算两个序列的内积。在二元函数对象中,我们可以根据需要定义不同的运算规则,以便满足不同的计算需求。
以下是一个示例代码,演示了初始值类型与结果类型不匹配时会导致结果出错:
int main() {
std::vector<int> v1 = {1, 2, 3};
std::vector<double> v2 = {1.1, 2.2, 3.3};
auto res = std::inner_product(v1.begin(), v1.end(), v2.begin(), 0);
std::cout << res << std::endl;
return 0;
}
初始值改为0.0
int main() {
std::vector<int> v1 = {1, 2, 3};
std::vector<double> v2 = {1.1, 2.2, 3.3};
auto res = std::inner_product(v1.begin(), v1.end(), v2.begin(), 0.0);
std::cout << res << std::endl;
return 0;
}
与之类似的例如std::accumulate
初始值改为0.0
int main() { std::vector<double> v = {1.1, 2.2, 3.3, 4.4, 5.5}; auto sum = std::accumulate(v.begin(), v.end(), 0.0); std::cout << "sum = " << sum << std::endl; return 0; }结果为16.5,正确

No comments yet.