如何将向量除以双倍数

How to divide vector by double?

本文关键字:向量      更新时间:2023-10-16

我想标准化(比例值在0和1之间)向量的速度。

normalized v(i)=v(i)-vmin/(vmax-vmin)

我的代码
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<double> velocity;
vector<double> results;
double vLower, vUpper, v1;
ifstream inputFile1("/home/milenko/gust/vel.dat");
if (inputFile1) {        
    double value;
    while ( inputFile1 >> value ) {
        velocity.push_back(value);
    }
}
vLower = *min_element(velocity.begin(), velocity.end());
vUpper = *max_element(velocity.begin(), velocity.end());
v1 = vUpper-vLower;
transform(velocity.begin(), velocity.end(), velocity.begin(), [vLower](double i) -> double { return i - vLower; });
transform (velocity.begin(), velocity.end(), v1, results, divides<double>());
for (auto c : results) { std::cout << c << std::endl; }
}

第一个变换工作得很好,它从每个向量元素中减去最小值。问题出在第二个,它应该把速度除以v1。

 In instantiation of ‘_OIter std::transform(_IIter1, _IIter1, _IIter2, _OIter, _BinaryOperation) [with _IIter1 = __gnu_cxx::__normal_iterator<double*, std::vector<double> >; _IIter2 = double; _OIter = std::vector<double>; _BinaryOperation = std::divides<double>]’:
v1.cpp:29:76:   required from here
/usr/include/c++/4.8/bits/stl_algo.h:4964:59: error: no match for ‘operator++’ (operand type is ‘std::vector<double>’)
       for (; __first1 != __last1; ++__first1, ++__first2, ++__result)
                                                           ^
/usr/include/c++/4.8/bits/stl_algo.h:4965:37: error: invalid type argument of unary ‘*’ (have ‘double’)
  *__result = __binary_op(*__first1, *__first2);
                                     ^
/usr/include/c++/4.8/bits/stl_algo.h:4965:2: error: no match for ‘operator*’ (operand type is ‘std::vector<double>’)
  *__result = __binary_op(*__first1, *__first2);

有什么办法解决这个问题吗?或者单次变换是否可行?

v1不应该在transform调用

transform (velocity.begin(), velocity.end(), back_inserter(results), 
bind(divides<double>(), placeholders::_1, v1));

但是既然你在第一次变换中使用lambda,那么在第二次变换中使用lambda也会更简单。

transform (velocity.begin(), velocity.end(), back_inserter(results),
[&v1](double v) { return v / v1; });

首先,你可以使用标准算法std::minmax_element来找到最小值和最大值,只遍历向量一次。

其次,有时编写基于范围的for循环比使用带有lambda表达式的算法更好,因为在第一种情况下,代码将更具可读性。

所以你可以写

auto minmax = std::minmax_element( velocity.begin(), velocity.end() );
auto x = *minmax.first / ( *minmax.second - *mimax.first );
for ( auto &value : velocity ) value -= x;

如果你需要创建一个新的向量,那么你可以写

auto minmax = std::minmax_element( velocity.begin(), velocity.end() );
auto x = *minmax.first / ( *minmax.second - *mimax.first );
vector<double> results;
resultr.reserve( velocity.size() );
for ( auto value : velocity ) results.push_back( value - x );