STL算法的可组合性 [英] Composability of STL algorithms
问题描述
STL算法在C ++中是一个非常有用的东西。
The STL algorithms are a pretty useful thing in C++. But one thing that kind of irks me is that they seem to lack composability.
例如,我有一个向量< pair< int ,int>>
并希望将其转换为仅包含第二的
向量< int> $ c>成员的对。这很简单:
For example, let's say I have a vector<pair<int, int>>
and want to transform that to a vector<int>
containing only the second
member of the pair. That's simple enough:
std::vector<std::pair<int, int>> values = GetValues();
std::vector<int> result;
std::transform(values.begin(), values.end(), std::back_inserter(result),
[] (std::pair<int, int> p) { return p.second; });
或者也许我想过滤向量
只有那些第一
成员是偶数的对。也很简单:
Or maybe I want to filter the vector
for only those pairs whose first
member is even. Also pretty simple:
std::vector<std::pair<int, int>> values = GetValues();
std::vector<std::pair<int, int>> result;
std::copy_if(values.begin(), values.end(), std::back_inserter(result),
[] (std::pair<int, int> p) { return (p.first % 2) == 0; });
但是如果我想同时做两个呢?没有 transform_if
算法,并使用 transform
和 copy_if
似乎需要分配临时向量
来保存中间结果:
But what if I want to do both? There is no transform_if
algorithm, and using both transform
and copy_if
seems to require allocating a temporary vector
to hold the intermediate result:
std::vector<std::pair<int, int>> values = GetValues();
std::vector<std::pair<int, int>> temp;
std::vector<int> result;
std::copy_if(values.begin(), values.end(), std::back_inserter(temp),
[] (std::pair<int, int> p) { return (p.first % 2) == 0; });
std::transform(values.begin(), values.end(), std::back_inserter(result),
[] (std::pair<int, int> p) { return p.second; });
这对我来说似乎比较浪费。我可以想到避免临时向量的唯一方法是放弃 transform
和 copy_if
,然后使用 for_each
(或常规for循环,无论哪种适合您的想法):
This seems rather wasteful to me. The only way I can think of to avoid the temporary vector is to abandon transform
and copy_if
and simply use for_each
(or a regular for loop, whichever suits your fancy):
std::vector<std::pair<int, int>> values = GetValues();
std::vector<int> result;
std::for_each(values.begin(), values.end(),
[&result] (std::pair<int, int> p)
{ if( (p.first % 2) == 0 ) result.push_back(p.second); });
我在这里缺少什么?是否有一个很好的方法来将两个现有的STL算法组合成一个新的STL算法而不需要临时存储?
Am I missing something here? Is there a good way to compose two existing STL algorithms into a new one without needing temporary storage?
推荐答案
您可以使用 Boost.Range适配器以实现组合。
You're right. You can use Boost.Range adaptors to achieve composition.
这篇关于STL算法的可组合性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!