【问题标题】:How to use Ruby's Enumerable .map method to do something similar to map in C++如何使用 Ruby 的 Enumerable .map 方法在 C++ 中执行类似于 map 的操作
【发布时间】:2012-12-07 03:47:21
【问题描述】:
map(-30, -89.75, 89.75, 0, 360) 

我正在寻找这样的东西:

  • -30 是输入值。
  • -89.75 到 89.75 是可能输入值的范围
  • 0 - 360 是要映射到的最终范围

有人告诉我有一种方法可以使用 http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map

.. 但它并不明显!

【问题讨论】:

  • 您确实需要举例说明您的预期输出。如何将 179.5 个输入值映射到 360 个输出值?
  • Enumerable map 函数似乎没有按照您的想法执行。

标签: c++ ruby enumerable


【解决方案1】:

如果我理解正确,我认为您只想将一个范围统一映射到另一个范围。所以,我们只需要计算它在输入范围内的距离,并返回输出范围的那一部分。

def map_range(input, in_low, in_high, out_low, out_high)
  # map onto [0,1] using input range
  frac = (input - in_low) / (in_high-in_low)
  # map onto output range
  frac * (out_high-out_low) + out_low
end

另外,我应该注意到map在ruby中的含义有点不同,更合适的描述可能是transform

【讨论】:

  • Enumerable#map 在 Ruby 中是 std::transform 在 C++ 中,但 map 是此操作的标准名称。不知道为什么 C++ 委员会认为为现有概念发明新术语是个好主意,例如 transform 代表 mapaccumulate 代表 fold 或“成员函数”代表“方法”。
猜你喜欢
  • 1970-01-01
  • 2015-08-29
  • 2012-09-05
  • 2016-03-21
  • 2015-05-12
  • 2014-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多