|
Boost : |
From: helmut.zeisel_at_[hidden]
Date: 2001-07-26 01:47:51
--- In boost_at_y..., helmut.zeisel_at_a... wrote:
> --- In boost_at_y..., "Vesa Karvonen" <vesa.karvonen_at_h...> wrote:
> > From: "Fernando Cacciola" <fcacciola_at_g...>
> >
> > As related issue, it is possible to write functions that return an
> object that
> > has a container-like interface (has begin() and end()), but refers
> to the
> > elements of the container differently.
>
To make that idea clearer,
I include a complete tested (VC++6) code example
("copy" is a completely rewritten code,
"sort", for simplicity, just wraps std::sort)
Helmut
template<typename Iterator> struct range
{
Iterator m_begin;
Iterator m_end;
range(Iterator begin, Iterator end): m_begin(begin), m_end(end) {}
Iterator begin() const {return m_begin;}
Iterator end() const {return m_end;}
typedef Iterator iterator;
};
template<typename Iterator> range<Iterator>
make_range(Iterator begin, Iterator end)
{
return range<Iterator>(begin,end);
}
template<typename Range> void sort(Range& r)
{
std::sort(r.begin(), r.end());
}
template<typename Range, typename Out> void copy(Range& r, Out res)
{
typename Range::iterator it=r.begin();
while(it != r.end())
{
*res++ = *it++;
}
}
#include <algorithm>
#include <vector>
#include <iostream>
int main()
{
std::vector<int> v;
v.push_back(2);
v.push_back(3);
v.push_back(1);
int w[]={3,2,4,1};
static const int n = sizeof(w)/sizeof(int);
sort(v);
copy(v,std::ostream_iterator<int>(std::cout," "));
std::cout << "\n";
sort(make_range(w,w+n));
copy(make_range(w,w+n),std::ostream_iterator<int>(std::cout," "));
return 0;
}
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk