简体   繁体   中英

Passing iterators to a function

I want to pass iterator of a vector of pointers to a function. I am not sure how to pass it.

Is this the right way of doing it:

main() {
    vector<MyObject*>::iterator it;

    for (it = added.begin(); it < added.end(); it++) {    
    string value = DoSomething(it)    
    }  
}
    string DoSomething(MyObject* a)
    {    
    if (a->isValid())
        Str = "0";
    ..
    ..   
    return str;
    }

The line:

string value = DoSomething(it)

should be:

string value = DoSomething(*it);

I want to pass iterator of a vector of pointers to a function.

string value = DoSomething(it);

You're trying to pass it correctly, but the function isn't written to use an iterator:

string DoSomething(MyObject* a)

This function wants a pointer... you can give it that:

string value = DoSomething(*it);

Or you can change your DoSomething function:

string DoSomething(vector<MyObject*>::iterator i)
{
     if ((*i)->isvalid())
         ...
}

If you really want to pass the iterator to the function, its parameter should also be an iterator:

#include <string>
#include <iostream>
#include <vector>

using namespace std;

string DoSomething(vector<string*>::iterator a) {
    string* entry = *a;
    cout << *entry << endl;
    return "blah";
}

int main() {
    vector<string*> added;
    string v1 = "v1";
    string v2 = "v2";

    added.push_back(&v1);
    added.push_back(&v2);

    vector<string*>::iterator it;

    for (it = added.begin(); it < added.end(); it++) {    
        string value = DoSomething(it);
    }  
}

You can see it in action here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM