dimitris93
dimitris93

Reputation: 4273

Get element at index from iterator

I have a function like this:

void func(vector<LatLng>::iterator it_start,
           vector<LatLng>::iterator it_end)
{
    int middle_index = (it_end - it_start) / 2;
    // how can I now get the element at 'middle_index' ?
}

Can I now get the element at middle_index without passing the vector itself as a parameter ?

Upvotes: 0

Views: 90

Answers (2)

flogram_dev
flogram_dev

Reputation: 42868

void func(vector<LatLng>::iterator it_start,
          vector<LatLng>::iterator it_end)
{
    int middle_index = (it_end - it_start) / 2;
    std::advance(it_start, middle_index);
    LatLng& mid = *it_start;
}

or simply

    LatLng& mid = *std::advance(it_start, (it_end - it_start) / 2);

or

    LatLng& mid = it_start[(it_end - it_start) / 2];

or using std::next:

    LatLng& mid = *std::next(it_start, middle_index);

Upvotes: 4

Rames
Rames

Reputation: 938

More reusable solution which works also for lists (if you make it template function or change parameter to std::list<T>::iterator) looks like:

void func(vector<LatLng>::iterator it_start,
          vector<LatLng>::iterator it_end)
{
    auto &mid = *std::next(it_start, std::distance(it_start, it_end)/2);
}

Upvotes: 1

Related Questions