gnp
gnp

Reputation: 257

use of iterators from the middle of the loop

i have a vector of vector "mydata". i want to iterate my data in negative direction. the iterator should be started from the middle to the beginning. i wish to use following way;

vector<vector<int> >::const_iterator points;
int i, k;

(lets assume k = 10)

for (i=k, points=mydata.begin()+k; i != -1; i--, points--){

     //do stuff
}

does this way is the proper way to iterate in backward? (I am using dev c++, so predicates and some modern commands cant be used.) Hope your suggestions to do this.

Upvotes: 0

Views: 3594

Answers (4)

MSalters
MSalters

Reputation: 179779

There are roughly two nice solutions. Either you just write the loop:

vector<int>::const_iterator i = v.begin() + 4;
do {
  // stuff with *i
while (--i != v.begin());

or use reverse iterators and the standard STL algorithms:

std::for_each(v.rend()-4, v.rend(), &stuff);

Upvotes: 0

LihO
LihO

Reputation: 42083

Since it's vector, you dont need to use iterator at all:

for (int k = 4; k >= 0; k--)
{
    // do something with v[k]
}

Example:

#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char** argv)
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    vector<int> v(arr, arr + 10);

    for (int k = 4; k >= 0; k--)
    {
        cout << v[k] << endl;
    }
}

output:

5
4
3
2
1

Upvotes: 0

Bojan Komazec
Bojan Komazec

Reputation: 9526

You can use std::vector::const_reverse_iterator. Here's the example of how to iterate backwards through the vector, starting from the middle:

#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v;

    for(int i = 0; i< 10; i++)
        v.push_back(i);

    std::vector<int>::const_reverse_iterator it = v.rbegin() + 5;


    for(;it != v.rend(); it++)
    {
        std::cout << *it << std::endl;
    }

    return 0;
}

Output:

4 
3 
2 
1 
0

Upvotes: 2

hmjd
hmjd

Reputation: 121961

A possible solution using reverse_iterators vector::rbegin() and vector::rend():

#include <iostream> 
#include <vector> 

int main()
{
    std::vector<int> v;
    for (int i = 0; i < 10; i++)
    {
        v.push_back(i);
    }

    for (std::vector<int>::const_reverse_iterator it = v.rbegin()+(v.size()/2);
         it != v.rend();
         it++)
    {
        std::cout << *it << "\n";
    }

    return 0;
}

Upvotes: 4

Related Questions