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

T33*_*33C 5 c++ iterator stl distance counting

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

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

有时,我对实际元素不感兴趣,只对输出元素的数量感兴趣.在这种情况下,复制元素会浪费内存和性能.是否有一个迭代器适配器,我可以使用它来计算和避免元素的副本?如果没有,你能建议这种适配器的通用实现吗?

T33*_*33C 0

感谢 @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;
}
Run Code Online (Sandbox Code Playgroud)