From: Michael Doubez on 11 Mar 2010 04:32 On 10 mar, 20:15, "Hicham Mouline" <hic...(a)mouline.org> wrote: > I have in input an STL container say std::vector<T> or std::list<T> called > my_container; > > Is there any advised style re filtering such a container, so that following > code can work only on a subset of that container , without knowing that it > has been filtered? > > Say the initial container has 100 elements sorted according to some > criteria, and the filter tells us to work only on the 20 elements. > > The filter could return to us a begin iterator and an end iterator to those > 20 elements only. > Subsequent code would then use only the iterators, and not functions like > my_container.front() > or > my_container.size() > > Is this a customary way? Or is there something that returns a view on the > original container? By filtering, I assume you are talking about a subrange of the container. It shouldn't be too hard to make a container that uses a range as its content: template <class TIteraror> class range_container { public: // container types typedef typename std::iterator_traits<TIteraror>::value_type value_type; typedef TIteraror iterator; typedef std::const_iterator<TIteraror> iterator; typedef typename std::iterator_traits<TIteraror>::reference reference; typedef const value_type& const_reference; typedef typename std::iterator_traits<TIteraror>::pointer pointer; typedef typename std::iterator_traits<TIteraror>::difference_type difference_type; typedef typename std::iterator_traits<TIteraror>::size_type size_type; // constructor range_container(iterator begin_range, iterator end_range) : _begin(begin_range) , _end (end_range) {} // do the same for copy constructor operator and swap iterator begin(){ return _begin;} iterator end(){ return _end; } // same for const flavor bool empty()const { return _begin == _end } size_type size()const { return std::distance(_begin,_end);} private: iterator _begin; iterator _end; }; Depending on the kind of iterator, you can even provide an augmented interface (reverse_iterator ...). -- Michael -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
First
|
Prev
|
Pages: 1 2 Prev: Can I store lambdas for the future? Next: std::search versus strstr for std::vector<char> |