输出迭代器适配器以计数但不复制 [英] Output iterator adapter to count but not copy

查看:116
本文介绍了输出迭代器适配器以计数但不复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There are various STL algorithms that rely on an output iterator to store the result of the algorithm.

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

For example, std::set_intersection will store all the common elements between two sorted ranges in an Output iterator that is then post incremented per element outputted.

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

Sometimes, I am not interested in the actual elements but only the number of output elements. In such cases it is a waste of memory and performance to copy the elements. Is there an iterator adapter that I can use to count and avoid the copy of the elements? If not can you suggest a generic implementation of such an adapter?

推荐答案

感谢@ecatmur的大量帮助回答和评论,我有以下解决方案,我邀请评论。我原本希望得到 boost :: make_function_output_iterator ,但似乎库中有一个错误,无法定义赋值运算符。

Thanks to a lot of help from @ecatmur answer and comments, I have the following solution, which I invite comments. I had hoped to get the boost::make_function_output_iterator working but it seems that there is a bug in the library which fails to define the assignment operator.

#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;
}

这篇关于输出迭代器适配器以计数但不复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆