Re: std::vector and const_iterator
On Mon, 26 Feb 2007 09:33:47 -0800, Trecius
<Trecius@discussions.microsoft.com> wrote:
Hello, Newsgroupains:
I have some problems with std::vector and const_iterator. I'm wondering if
you could assist me in solving them.
First, for simplicity, suppose I have a vector of integers.
std::vector<int> vItems;
Also, suppose I have two constant iterators, viStart and viEnd.
std::vector<int>::const_iterator viStart;
std::vector<int>::const_iterator viEnd;
The iterators define a specified range in the vector. One, how can I
determine if the const_iterator is valid? For instance... if (viEnd != NULL
|| viStart != NULL).
It's the same with all container iterators; compare to the relevant end().
There is no "null" value for iterators, which only have meaning relative to
some container. Thus, to compare iterators, they must have assigned values,
and they must not have been invalidated by some operation on the container.
Second, I'm trying to iterate over the vector in specified jumps. For
example, I'd like the user to input an integer, which will be the input
interval. Starting at viStart to viEnd, I want to make a const_iterator to
iterate over the vector at the specified interval.
For example, if the user enters a 3, starting from viStart, the constant
iterator will jump three pointers and output the integer and then jump
another three pointers and output the integer. This process continues until
(1) the const_iterator surpasses the viEnd, or (2) the const_iterator goes
beyond the range of the entire vector. However, I don't know how to check
these statements? Anyone know how to do it USING CONST_ITERATOR and not the
.size() of the vector?
I think valarray offers something like that as standard, but for vector,
you can use pointer-like addition to move from element to element,
comparing to end() all along the way. More generally, you can use
std::advance to perform the movement. You could create a special stride
iterator class such that each increment moves a certain number of elements
defined by a template parameter. Check out boost.org; someone may have
already written it.
--
Doug Harrison
Visual C++ MVP