Reputation: 1
When I traverse a list of objects and I have to return the pointer to one of my object when I have a iterator pointing to it, how I do so ? In short can one tell what should I put in the place of ???
#include <iostream>
#include <list>
using namespace std;
class Node
{
private:
int name;
public:
Node() : name(0) {}
Node(int n) : name(n) {}
int getName() {return name;}
void setName(int n) {name = n;}
};
list<Node> mylist;
Node* getNodeObjectPointer(int n)
{
Node* toBeReturned = NULL;
for(list<Node>::iterator it=mylist.begin(); it != mylist.end(); it++)
{
if(((*it).getName()) == n)
toBeReturned = ???
}
return toBeReturned;
}
int main()
{
Node* a = new Node(1);
mylist.push_back(*a);
Node* b = new Node(2);
mylist.push_back(*b);
Node* myPointer = getNodeObjectPointer(1);
return 0;
}
Upvotes: 0
Views: 4918
Reputation: 311078
Node* getNodeObjectPointer( int n )
{
list<Node>::iterator it = mylist.begin();
while ( it != mylist.end() && it->getName() != n ) ++it;
return ( it == mylist.end() ? NULL : &*it );
}
It would be much better and simpler if you wrote in main
int main()
{
mylist.push_back( 1 );
mylist.push_back( 2 );
Node* myPointer = getNodeObjectPointer(1);
return 0;
}
Also member function getName
should be declared as
int getName() const {return name;}
Upvotes: 0
Reputation: 21803
Your code to add objects to the list leaks memory and it is needlessly inefficient. Use this instead
mylist.push_back(Node(1));
mylist.push_back(Node(2));
Your function should be
Node* getNodeObjectPointer(int n)
{
Node* toBeReturned = NULL;
for(list<Node>::iterator it=mylist.begin(); it != mylist.end(); it++)
{
if(((*it).getName()) == n)
{
toBeReturned = &*it;
break;
}
}
return toBeReturned;
}
If you remove that node from the list, the pointer becomes invalid.
Upvotes: 1
Reputation: 385295
You can obtain a pointer from an iterator like this:
Node* getNodeObject(int n)
{
for (list<Node>::iterator it = mylist.begin(); it != mylist.end(); it++) {
if ((it->getName()) == n)
return &*it; // this is the key, if you really want a pointer
}
return NULL;
}
But I'd return a reference instead (throwing an exception on failure to find). You could even just return the iterator. Or use std::find
…
Related, this leaks like a sieve:
Node* a = new Node(1);
mylist.push_back(*a);
Just write:
Node a(1);
mylist.push_back(a);
or even:
mylist.push_back(Node(1));
Upvotes: 6
Reputation: 16338
Your list should be a list of pointers to Node
.
list<Node*> mylist;
It makes no sense to do things like creating objects on the heap, dereferencing them and putting values on stack and then returning pointers to those objects.
Upvotes: -4
Reputation: 4939
What you should do is dereference the iterator and find its address.
return &(*itr);
If you can you could also alter the code to return the iterator instead of a raw pointer.
Upvotes: 1