Reputation: 2569
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;
}
Upvotes: 1
Views: 1318
Reputation: 6308
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.
Upvotes: 2
Reputation: 106096
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())
...
}
Upvotes: 3
Reputation: 4659
The line:
string value = DoSomething(it)
should be:
string value = DoSomething(*it);
Upvotes: 4