使用“变换”创建增加的向量

Using `transform` to create an increasing vector

本文关键字:增加 向量 创建 变换 使用      更新时间:2023-10-16

我正在尝试使用transform进行增加的向量,并且不得做到正确。我想使用变换。我在做什么错?

ps-我将使用C 11标准和G 。

#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
    std::vector<double> x(10);
    x.front() = 0.0;
    double h = 0.1;
    std::transform(x.begin(), x.end() - 1, x.begin() + 1, [h](unsigned int xn) {return xn + h;});
    std::cout << x.at(3) << " " << x.at(9) << std::endl;
}

当使用计算下一个

时,转换为unsigned int的转换正在截断每个值

std::transform-使用Unary Operator

std::transform将给定功能应用于范围,并存储 从d_first。

开始另一个范围

通过std::transform和封闭,您可以初始化std::vector

#include <algorithm>
#include <iostream>
#include <vector>
int main() {
  std::vector<double> v(10);
  const double step = 0.1;
  std::transform(begin(v), end(v), begin(v),
                 [step](const double value) { return value + step; });
  for (const auto value : v) {
    std::cout << value << ' ';
  }
}

std::generate-通过可呼叫

增量

在范围内分配每个元素[首先,最后)一个由 给定的功能对象

如果您想要自定义增量,则可以使用std::generate

#include <algorithm>
#include <iostream>
#include <vector>
int main() {
  std::vector<double> v(10);
  double seed = 0.0;
  std::generate(begin(v), end(v), [&seed]() {
    const auto ret = seed;
    seed += 0.1;
    return ret;
  });
  for (const auto value : v) {
    std::cout << value << ' ';
  } // outputs: 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 
}

std::iota-通过++value

增量

略有主题。您可以为0.1提供CC_11的类型,但对于读者而言,它不是直观的。

您可以使用依赖operator++std::iota

以依次增加的值填充[第一,最后一个),从价值开始,然后重复评估++value

您的情况中的代码将是:

#include <numeric>
#include <iostream>
#include <vector>
int main() {
  std::vector<double> v(10);
  std::iota(begin(v), end(v), 0.0);
  for (const auto value : v) {
    std::cout << value << ' ';
  } // outputs: 0 1 2 3 4 5 6 7 8 9
}

lambda声明了错误类型的参数

[h](unsigned int xn) {return xn + h;});
    ^^^^^^^^^^^^^^^

应该有

[h]( double xn ) {return xn + h;});
    ^^^^^^^^^^^

这是其他一些编写的方法。您可能会发现它们更具表现力。

#include <vector>
#include <algorithm>
#include <numeric>
std::vector<double> create1(double i, double h)
{
  std::vector<double> v(10);
  std::generate(std::begin(v), std::end(v), 
                [&]() mutable
  {
    auto result = i;
    i += h;
    return i;
  });
  return v;
}
std::vector<double> create2(double i, double h)
{
  std::vector<double> v(10);
  for (std::size_t x = 0 ; v.size() ; ++x) {
    v[x] = i + h * x; 
  }
  return v;
}
std::vector<double> create3(double i, double h)
{
  struct emitter
  {
    emitter& operator++() {
      i += h;
    }
    operator double() const { return i; }
    double i, h;
  };
  std::vector<double> v(10);
  std::iota(v.begin(), v.end(), emitter { i, h });
  return v;
}
int main()
{
  auto v1 = create1(0, 0.1);
  auto v2 = create2(0, 0.1);
  auto v3 = create3(0, 0.1);
}

不管它可能遇到的任何其他问题,您的实现都有微妙的缺陷:它依赖于已经设置的向量中的每个先前值。

这不能保证可行,因为std :: transform()不能保证操作员的额外申请。