C++ return value question

Started by
5 comments, last by choboNo1 18 years, 5 months ago
In C++: I have an array of objects of type X. In function F, i have to loop through the array and try to find an object that has a member that matches the parameter. If i found it, then return that object. my question is, what do i return if i can't find the object? In java.. you can just return null.. but i don't know what to return in C++. I tried to return NULL.. but that doesnt seem to work. so my function would be like X &Find_Object(String name); Thanks in advance.
Advertisement
So if you have a reference, the idea is that the reference is never "invalid", which in this case is NULL.

If you want to describe returning a value that can be invalid, try using a pointer, and returning NULL.

T* find(something)

In java, everything is a pointer, basically, so you can have that. In C++ you gotta explicitly use a pointer.
You could throw an exception, although you may not consider that appropriate for this case.
The C++ Standard library containers handle it by having their find() functions return an iterator and then return the end() iterator on failure.

You could also return something like a std::pair holding a bool and a reference. Return true and a reference to the correct element if the function suceeds, return false and a reference to a dummy object if it fails.

Options:

1) References. Throw an exception if you can't find it (see std::vector::at)
2) Pointers. Set to NULL if you can't find it (see C library?)
3) Iterators. Set to .end() if you can't find it (see std::find)
4) Value. Set to something indicating "invalid" (see C file i/o API)
5) std::pair< value , bool > (see std::set/map::insert)
6) boost::optional< value > (see boost.org)
7) Value. Set a value such that GetMyAPIsLastError will return something. (see C library)
Quote:Original post by choboNo1
In C++:

....

so my function would be like

X &Find_Object(String name);


Use the standard library generic algorithms, in particular std::find/find_if yes you can use them with C-style arrays but if you need a dynamic array you should be using std::vector/deque e.g.

#include <algorithm> //find_if#include <vector>#include <string>struct foo {   std::string s;   //.....};//....struct foo_by_str {   const std::string& key;   foo_by_str(const std::string& s): key(s) {}   bool operator()(const foo& f) const {      return key == f.s;   }};int main() {   typedef std::vector<foo> foos;    foos fs;   //.....   std::string key = .....;   foos::const_iterator result           = std::find_if(fs.begin(), fs.end(), foo_by_str(key));   if(result != foos.end())      // then a match was found   else      // no match was found   //....}


Last thing don't try to use C++ like Java, things work differently in the two, have different idioms and techniques, you will only be using C++ ineffectively if you do.
Thanks guys for all the help!

This topic is closed to new replies.

Advertisement