Non-container Iterators
My area of programming is DSP. I write things like filters, oscillators,
envelopes, etc. I've been looking at STL iterators, and what's struck me is
that if I can find ways to model my code using STL's iterator conventions, I
could possibly make my code more economic while probably losing little to no
efficiency.
As an example, an oscillator will have a "phase accumulator." So typically
in a loop I will have something like this:
phaseAccumulator += phaseIncrement;
if(phaseAccumulator >= 1.0f)
{
phaseAccumulator -= 1.0f;
}
output = waveform(phaseAccumulator);
It occurred to me that I could have a phase accumulator iterator. My code
would turn into this:
phaseAccumulator++;
output = waveform(*phaseAccumulator);
Much more compact. Or even better:
std::transform(phaseFirst, phaseLast, outputBuffer, SineWaveform());
Down to just one line of code. Ok, so far, so good. But there is a gray area
I'm concerned about.
I need to keep track of the phase. The phase is state that needs to persist
across iterations. This means that I need to give the iterator a pointer to
the phase variable when I create it so that as it's iterating, it's also
modifying the phase variable. Something like:
// Inside my Oscillator class somewhere:
it = PhaseIterator it(&phase, increment);
// Inside the PhaseIterator class:
PhaseIterator &operator++()
{
*phase += increment;
if(phase >= 1.0f)
{
phase -= 1.0f;
}
return *this;
}
This works, but it means that I can only use one phase iterator at a time.
That's actually not a problem for me since the iterator is only being used
internally by the Oscillator class, but my question is whether this violates
the spirit of STL iterators. Is there a category of iterators (Input
Iterators, perhaps?) that restrict you to using only one iterator at a time
over a collection?
Advancing an iterator doesn't usually involve changing the collection the
iterator belongs to. However, in this case, the collection is the phase
values belonging to the oscillator; the iterator is actually generating the
phase values that drive oscillation. I like this approach, but was wanting
to get some thoughts on this from others.