c++ - C++ copy_if、transform 等的函数版本

标签 c++ stl-algorithm

例如的非迭代器版本all_of 可以写成:

template <class Container, class UnaryPredicate>
bool all_of(Container s, UnaryPredicate f) {
  return all_of(s.begin(), s.end(), f);
}

但我认为你不能对返回容器的算法做同样的事情?

template <class Container, class UnaryPredicate>
Container copy_if(Container, UnaryPredicate);

我最接近的实现是使用 vector 来保存中间结果,但由于缺乏任何方法来为 vector 提供模板参数而绊倒。我有什么遗漏的吗?

最佳答案

您应该使用std::insert_iterator而不是使用 vector 来保存临时文件:

template <class Container, class UnaryPredicate>
Container copy_if(Container const& input, UnaryPredicate const& up) {
    Container tmp;
    std::copy_if(input.begin(), input.end(),
                 std::insert_iterator<Container>(tmp, tmp.begin()), up);
    return tmp;
}

std::insert_iterator 需要您的容器具有 insert() 方法,这不是Container 的要求。但这都是 SequenceContainer 的要求和 AssociativeContainer (表不完整,但[associative.reqmts]需要它(表102))。


如果您确实想使用 vector 并且您的所有Container都遵循 Container概念,那么您可以使用以下方式访问它们的值类型:

typename Container::value_type

例如:

std::vector<typename Container::value_type>

关于c++ - C++ copy_if、transform 等的函数版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36724819/

相关文章:

c++ - 内存泄漏 - 套接字或字符串相关?

c++ - 部分模板特化数组使用

c++ - 如何将 'cv::Mat' 转换为 'double'?

algorithm - 为什么是 `copy_n` 、 `fill_n` 和 `generate_n` ?

c++ - 为什么 fill_n() 不适用于 vector.reserve()?

c++ - 具有为实例化固定但随模板参数变化的参数数量的模板方法

c++ - Tandy 1000 PC SX 的 C 或 C++ 编译器?

algorithm - LCS算法(示例)

c++ - std::equal_range 提示 "sequence not ordered"

c++ - 有没有插入然后排序的替代方法