tags:

views:

57

answers:

3

can somebody explain I can I return list iterator?

list<Account>::iterator Company::findAccount(int id){
    for(list<Account>::iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){
        if(i->getID() == id){
            return i;
        }
    }
    return 0;
}

and also is it good practice, to return list iterator?

edited

also can use this function in the statesments:

if(findAccount(id)){
            throw "hey";
            return;
        }
+1  A: 

Algorithms from <algorithm> header, find for example, return iterators, so it's ok. But you should return iterator, like listOfAccounts.end() instead of 0 if you need to indicate error.

Paul
+1  A: 

Yes, you can. Yes it is. However, if you want to return an invalid iterator (as in your example, when no element is found) you should not return 0, but return listOfAccounts.end().

Michael Ulm
+2  A: 

In your case returning an iterator exposes internals of the class, and that is almost always a bad thing. As @Paul said in his answer, some STL-algorithms return iterators. However, they return iterators on the input-collection. From the name of your method I guess it would be the best thing to return an object or a const reference.

About your edit, you may want to look into the Null Object Pattern. Alternatively you can provide a method DoesAccountExist. If a call to that method returns true, a call to findAccount must succeed, otherwise it can throw an exception.

Space_C0wb0y
@Space_C0wb0y: ok. but what about 0, I can't return 0 as a reference as I know
helloWorld
Like i wrote, look up the Null Object Pattern.
Space_C0wb0y