Syntactic Fructose
Syntactic Fructose

Reputation: 20074

function similar to advance that returns an iterator?

Is there a function similar to advance, but will return an iterator instead of having a void return type? I want to have a function call like:

//...
[&value](InIter part_begin, std::size_t part_count)
        {
            difference_type ret = 
                std::count(part_begin, std::advance(part_begin,count), value);
            return ret;
        },

but advance is a void return type function, so i'm currently doing

//...
[&value](InIter part_begin, std::size_t part_count)
        {
            InIter end = part_begin;
            std::advance(end,part_count);
            difference_type ret = std::count(part_begin, end, value);
            return ret;
        },

it's important to note I cannot just do part_begin + count, this will not work for some of the iterators I am working with which forces me to currently use std::advance. Is there any cleaner way of doing this?

Upvotes: 1

Views: 113

Answers (2)

nosid
nosid

Reputation: 50044

You can use std::next to get an iterator advanced by a given number of elements. In contrast to std::advance, std::next does not change the passed iterator itself.

[&value](InIter part_begin, std::size_t count) {
        difference_type ret = 
            std::count(part_begin, std::next(part_begin,count), value);
        return ret;
    },

Upvotes: 5

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

Yes, it's called std::next. It doesn't modify its argument.

Upvotes: 6

Related Questions