Non-container Iterators

L

Leslie Sanford

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

First website practice project advisement 4
2 Iterators/Iterator Math 1
Container of iterators (newbie) 2
Selenium c++ help 0
Subtyping iterators 5
Building a Large Container 26
sorts and iterators 10
iterators 16

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top