tags:

views:

84

answers:

4
I have this snippet of the code

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

Is this right way to return 0 if I didn't find appropriate account? cause I receive an error:

no match for 'operator!' in '!((Company*)this)->Company::findAccount(id)'

I use it this way:

if(!(findAccount(id))){
            throw "hey";
          }

thanks in advance

+1  A: 

You cannot return a "null reference" in C++, because there is no such concept in this language.

If either an Account or no Account can be the result, one way to do it is to return an Account *.

Daniel Daranas
+1  A: 

Another way (except for Account*) would be to return special Account::empty object, and/or test using account.IsEmpty().

queen3
A: 

Why don't you use a standard algorithm like std::find_if.

Edit: Explanation of find_if.

Here is the reference for find_if algorithm. http://cplusplus.com/reference/algorithm/find_if/

bool isEqual(int id1, int id2) {
   return id1 == id2;
}

void foo() {
    std::list<Account> accountList;
    // Fill this list here.

    list<Account>::iterator it = std::find_if(accountList.begin(), accountList.end(), bind(isEqual, idYouSearch, _1));

    Account ac = *it;
}

You might need additional includes for bind and _1 placeholder. Propably there is a std Predicate for isEqual and you could use this instead.

Egeria
can You explain it plese, I thought that list doesn't have such algorithm
helloWorld
the algorithms don't belong to the containers. All standard containers have iterators which you can use with the standard algorithms.
Egeria
+4  A: 

There is no such thing as a null reference. The standard says:

A reference shall be initialized to refer to a valid object or function. [ Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.

FredOverflow