Reputation: 39810
is there a way to do what I'm trying to do without using pointers or references?
Here's the code:
Node getSmallest() {
if (openList.empty())
return 0; // syntax error
// some other code
}
Upvotes: 4
Views: 2080
Reputation: 30035
You can use boost::optional
to return an optional value. Or wait for C++14 and use std::optional
.
Upvotes: 7
Reputation: 4092
The return type of your getSmallest() function is defined as a Node object, which in C++ means that returned expression must be of type Node, and at runtime the returned object's memory will be copied back to the caller.
Since, you can not return integer 0.
What you can do, instead, is defining a particular instance object for Node that represents a NULL Node. This basically depends on Node's definition, supposing the following:
class Node {
// Some representative field
int a;
// Some basic constructor
Node(int a){
this->a = a;
}
}
You can define a NULL Node in a way similar to:
class Node {
// Some representative field
int a;
// Some basic constructor
Node(int a){
this->a = a;
}
static Node NULL_NODE(-1);
}
The above example assumes that you actually never assign field a
with the value -1 in other Node objects. If -1 does not fit your purpose, you can choose a value you assume to never use.
If you have multiple fields in the node, you can represent the NULL_NODE with a combination of values.
EDIT: As innosam points out, you can also (and probably better) add a boolean field to the Node class to represent if the node is NULL or either.
With the above said, you can now implement your function like this:
Node getSmallest() {
if (openList.empty())
return Node.NULL_NODE; // syntax error
// some other code
}
Otherwise, you can use a third-party tool that allows you do to the same thing. Refer to other people's answers for this case.
Upvotes: 2
Reputation: 437
It seems you want to return the copy of the Node
object, when your code is successful.
struct Node{
int a;
bool isEmpty_;
Node(bool isEmpty):isEmpty_(isEmpty)
};
Node getSmallest() {
if (openList.empty())
return Node(false);
// some other code
}
There is no other way, you have to return an object, which internally could have a isEmpty
flag set to signify the error.
Upvotes: 3