2

Using mid-loop iterators

 2 years ago
source link: https://www.codesd.com/item/using-mid-loop-iterators.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Using mid-loop iterators

advertisements

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.


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

Tags iterator

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK