returning an object pointed by iterator

1
2
3
4
5
6
7
8
9
10
11
		const std::vector<Account>& getExistingAccount(const std::vector<Account>& acc,const std::string& username)
		{
			for ( std::vector<Account>::const_iterator iter = acc.begin(); iter != acc.end(); iter++ )
			{
					if(iter->getUsername() == username)
					{
						return *iter;
					}
			}
			return *acc.end();
		}

can someone help me about this
this spits out:

invalid initialization of reference of type 'const std::vector<Account>&' from expression of type 'const Account'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
		// const std::vector<Account>& getExistingAccount(const std::vector<Account>& acc,const std::string& username)
		const Account& getExistingAccount( const std::vector<Account>& acc, const std::string& username)
		{
			for ( std::vector<Account>::const_iterator iter = acc.begin(); iter != acc.end(); /* iter++ */ ++iter )
			{
					if(iter->getUsername() == username)
					{
						return *iter;
					}
			}

			// return *acc.end(); // can't dereference acc.end()
                        throw std::domain_error( "not an existing account" ) ;
		}
thanks jlborger. didnt notice i was returning an object when my return type is a vector of that object.
and yea about the return *acc.end();.


is this a good alternatives if the function didnt found any account?
return Account()? so if it returns empty then an account doesnt exist.

edit:
nvm, the alternative wont work, it will just be segfault the moment the function ends, because it returns a reference to that Account().

thanks again.
Last edited on
Topic archived. No new replies allowed.