Reputation: 102
I need to return pointer for a member in a list, and if the required member is not there I get a null pointer (or any other indication)
list<LINKS>::iterator find_link(list<LINKS> &link, char* ID)
{
list<LINKS>::iterator link_index;
LINKS link_i;
link_index = link.begin();
for (int i = 0; i < link.size(), i++)
{
link_i = *link_index;
if (!strcmp(link_i.ID, ID)) { return link_index; };
link_index++;
};
cout << "Node outsession does not exist " << ID;
return nullptr; // ERROR (nullptr is not the same type as list<LINKS>::iterator)
};
I added the error message (cout << "Node outsession does not exist " << ID;
) to indicate if the link is not found, but I need to indicate that for the caller function.
How can I do that ? Thanks
Upvotes: 0
Views: 658
Reputation: 2234
nullptr
is not an iterator, so you can't return it in a function that returns an iterator value
std::find(begin(), end(), value)
returns an iterator and returns end()
if the value is not found. To check it you say:
std::list<int> l;
...
auto found = std::find(l.begin(), l.end(), 6); // returns an std::list::iterator
if (found == l.end())
{
std::cout << "Bogus!" << std::endl;
}
...
There are other examples in which the container find returns a value, and uses a special value for "not found"
std::string s = "go to the store";
auto found = s.find('x'); // returns a size_t index into the string
if (found == std::string::npos)
{
std::cout << "Bogus!" << std::endl;
}
Returning nullptr
would make sense if your function returned a pointer. In that case, nullptr
would be a reasonable sentinel value for not found.
Upvotes: 2
Reputation: 600
The normal accepted way to return 'value not found' when searching a list is to return an iterator pointing to the end of the list. In this case link.end()
This is exactly how the std::find
algorithm from <algorithm>
behaves.
In your calling function test the returned iterator as follows:
list<LINKS>::iterator itr = find_link(list, "Funyuns");
if( itr == list.end() ) {
std::cout << "You are all out of Funyons :-(" << std::endl;
}
Upvotes: 1