Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

c++ - Skip an entry of a random iterator

Suppose we have a function foo that does something to all the elements between *firsta and *lastb:

foo(RandomAccessIterator1 firsta,RandomAccessIterator1 lasta){
    for (RandomAccessIterator1 it=firsta;it!=lasta+1;it++){
            //here stuff happens...
    }    
}

question a): is there a way to skip an index firsta<i<lastb by only modifying the inputs to foo --e.g. the random iterators, in other words without changing foo itself, just its input?

--Unfortunately the index I want to skip are not in the edges (they are often deep between firsta and lasta) and foo is a complicated divide&conquer algorithm that's not amenable to being called on subsets of the original array the iterators are pointing to.

question b): if doing a) is possible, what's the cost of doing that? constant or does it depend on (lasta-firsta)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The best way to do this would be to use an iterator that knows how to skip that element. A more generalized idea though, is an iterator that simply iterates over two separate ranges under the hood. I don't know of anything in boost that does this, so, here's one I just whipped up: http://coliru.stacked-crooked.com/a/588afa2a353942fc

Unfortunately, the code to detect which element to skip adds a teeny tiny amount of overhead to each and every iterator increment, so the overhead is technically proportional to lasta-firsta. Realistically, using this wrapper around a vector::iterator or a char* should bring it roughly to the same performance level as std::deque::iterator, so it's not like this should be a major slowdown.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...