我有以下功能:
/* 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我可以这样做并检查NULL是否存在交叉点:
vector<double> v = intersection(pos, dir);
if(v == NULL)
/* Do something */
else
/* Do something else */
Run Code Online (Sandbox Code Playgroud)
如果这是不允许的/糟糕的编码实践,我可以采取的另一种方法是什么?
NULL真的只是一个指针的概念。由于我们有一个容器,我们可以检查其他内容,即容器是否为empty。如果是,那么我们知道我们没有元素,如果不是,那么我们知道有东西要处理。这让您可以编写类似的代码
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
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它
vector<double> v = intersection(pos, dir);
if(v.empty())
/* Do something */
else
/* Do something else */
Run Code Online (Sandbox Code Playgroud)
另请注意,如果您想获得一组交集,您可以std::set_intersection像这样使用和使用它
Run Code Online (Sandbox Code Playgroud)#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 << ' '; }输出:
Run Code Online (Sandbox Code Playgroud)5 7