Re: filtering (a view on) an STL container
In article <4b97d862$0$284$14726298@news.sunsite.dk>,
"Hicham Mouline" <hicham@mouline.org> wrote:
Hello,
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?
A function like this might be useful to you:
template < typename C >
pair<typename C::iterator, typename C::iterator>
partial_container(C& container, int count)
{
pair<typename C::iterator, typename C::iterator> result;
result.first = container.begin();
result.second = container.begin();
advance(result.second, count);
return result;
}
// sample usage
struct gen
{
int i;
gen(): i(0) { }
int operator()() { return i++; }
};
int main()
{
typedef vector<int> vec_t;
vec_t foo(100);
generate(foo.begin(), foo.end(), gen());
pair<vec_t::iterator, vec_t::iterator> its =
partial_container(foo, 20);
copy(its.first, its.second, ostream_iterator<int>(cout, " "));
cout << '\n';
}
However, if your container is sorted and you want all the elements that
satisfy a particular sort criteria, then upper_bound would be a better
to choice.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]