我可以为vector <double>函数返回NULL吗?

时间:2017-06-14 18:21:25

标签: c++ vector null

我有以下功能:

/* 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;
   }
} 

我是否可以执行此操作并检查NULL是否存在交叉点:

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

如果不允许这样做/编码不好,我可以采取另一种方式吗?

1 个答案:

答案 0 :(得分:4)

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
    }
} 

然后你可以像

一样使用它
vector<double> v = intersection(pos, dir);
if(v.empty())
    /* Do something */
else
    /* Do something else */

另请注意,如果您想获得一个交叉点,可以使用std::set_intersection并使用它

#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 << ' ';
}
     

输出:

5 7
相关问题