 David -3 years ago 49
C++ Question

# Can I return NULL for vector<double> function?

I have the following function:

``````/* Calculate if there is an intersection with given intial position and
direction */
vector<double> intersection(vector<double> startPos, vector<double> direction)
{
if(there is intersection)
return (intersection coordinates);
else {
return NULL;
}
}
``````

Could I do this and check against
`NULL`
if an intersection exists:

``````vector<double> v = intersection(pos, dir);
if(v == NULL)
/* Do something */
else
/* Do something else */
``````

If this is not allowed/bad coding practice, what is another way I may go about this? NathanOliver
Answer Source

`NULL` really is only a concept of pointers. Since we have a container we can check something else, namely, whether or not the container is `empty`. If it is then we know we have no elements and if it is not then we know there is stuff to process. That lets you write code like

``````vector<double> intersection(vector<double> startPos, vector<double> direction)
{
if(there is intersection)
return (intersection coordinates);
else {
return {}; // this means return a default constructed instance
}
}
``````

and then you can use it like

``````vector<double> v = intersection(pos, dir);
if(v.empty())
/* Do something */
else
/* Do something else */
``````

Also note that if you want to get a set intersection you can use `std::set_intersection` and use it like

``````#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> v1{1,2,3,4,5,6,7,8};
std::vector<int> v2{        5,  7,  9,10};
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<int> v_intersection;
std::set_intersection(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(v_intersection));
for(int n : v_intersection)
std::cout << n << ' ';
}
``````

Output:

``````5 7
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
Latest added