输出迭代器适配器以计数但不复制

T33C

有多种STL算法依赖于输出迭代器来存储算法的结果。

例如,std::set_intersection将所有两个排序范围之间的公共元素存储在Output迭代器中,然后对每个输出的元素进行后期递增。

有时,我对实际元素不感兴趣,而仅对输出元素的数量感兴趣。在这种情况下,复制元素会浪费内存和性能。是否有一个迭代器适配器,我可以用来计数并避免元素的复制?如果不能,您是否可以建议这种适配器的通用实现?

T33C

感谢@ecatmur的回答和评论提供的大量帮助,我得到了以下解决方案,欢迎您提出评论。我曾希望能开始boost::make_function_output_iterator工作,但似乎库中有一个错误未能定义赋值运算符。

#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
#include <cassert>

class counting_output_iterator 
{
public:  
  counting_output_iterator& operator=(const counting_output_iterator&) { return *this; };
  explicit counting_output_iterator(std::size_t& count) : m_count(count) {}
  template<typename T> void operator=(const T&) {}; //NULL op
  using iterator_category = std::output_iterator_tag;
  using value_type = void;
  using difference_type = void;
  using pointer = void;
  using reference = void;      
  counting_output_iterator& operator*() { return *this; }
  counting_output_iterator& operator++() { ++m_count; return *this; }  
  std::size_t&  m_count;
};

int main(int, char*[])
{   
    std::vector<int> arr{ 1,2,3,4 };
    std::size_t count = 0;  
    std::copy(std::begin(arr), std::end(arr), counting_output_iterator{ count } );
    assert(count == 4u);
    return 0;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章