“地图”的STL名称函数式编程函数
我希望能够编写类似的东西
char f(char);
vector<char> bar;
vector<char> foo = map(f, bar);
transform
函数看起来很相似,但它不会自动生成结果集合的大小。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在
中使用std::back_inserter
,尽管在前面提供大小会更有效。例如:You can use
std::back_inserter
in<iterator>
, although providing the size in front is more efficient. For example:这个问题是在 C++11 标准生效之前提出的……现在我们有
std::transform()
作为函数式编程“地图”的(丑陋)等价物。使用方法如下:This question was asked before the C++11 standard went into effect... nowadays we have
std::transform()
as the (ugly) equivalent of a functional programming 'map'. Here's how to use it:为了使这项工作正常进行,您需要注意以下几点:
map
函数不应该执行这项工作。相反,它应该将其参数保存在临时对象中(在您的情况下,这将是 class map::resultmap::result
临时文件应该有一个template运算符 T
转换。map::result
分配给std::vector
时,此转换是唯一可行的。class map::result中>::operator vector
您拥有输入和返回类型以及映射函数。此时您可以有效地转换输入。代码
使用如下:
To make this work, you'll need the following observations:
map
function should not do the work. Instead, it should save its arguments in a temporary object (in your case, that would be an instance ofclass map::result<char(*)(char), vector<char> >
)map::result
temporary should have antemplate <typename T> operator T
conversion.map::result
is assigned to astd::vector<char>
, this conversion is the only viable.class map::result<char(*)(char), vector<char> >::operator vector<char>
you have the input and return type, and the mapping function. At this point you can effectively transform the inputs.<edit>
Code
Use like this:
您可以使用类似的内容来模仿上面的映射语法
You can mimic the map syntax above with something like
std::transform
函数可以完成这项工作,但在某些情况下性能不佳。我建议使用 while 循环并预先保留大小。这个函数可以很容易地更改为与字符串或任何可映射的东西一起使用。调用函数,其中
array
是您想要的 std::vector地图。
运行地图 100 000 000
std::transform
花费了约 6.15 秒,而 while 循环版本花费了约 3.90 秒
The
std::transform
function does the job, but isn't performant in some cases. I would suggest using awhile
loop and reserving the size before hand. This function can easily be changed to be used with strings or any thing mappable for that matter.Calling the function where
array
is the std::vector you want tomap.
Running map on 100 000 000
with
std::transform
took ~6.15sthe while loop version took ~3.90s