【问题标题】:Can I return NULL for vector<double> function? [duplicate]我可以为 vector<double> 函数返回 NULL 吗? [复制]
【发布时间】:2017-06-14 18:21:24
【问题描述】:

我有以下功能:

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

如果这是不允许/不好的编码习惯,我还有什么方法可以解决这个问题?

【问题讨论】:

  • 向量不可能为NULL,但可以为空()。
  • 也许看到这个问题:stackoverflow.com/q/29460651/10077
  • 没有。 NULL 通常与指针一起使用。但是,您可以返回一个空向量并在另一边验证它是否为空。
  • 您也可以返回一个指向向量的(共享)指针,但@NeilButterworth 的评论可能是首选。
  • 您有 2 个选项:1 返回一个空向量。 2 抛出异常,因为函数无法履行其承诺。这取决于具体情况,哪个更合适。

标签: c++ vector null


【解决方案1】:

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

【讨论】:

  • 但在某些情况下,空向量与代码中的空值存在明显差异
  • 在这种情况下,使用std::optional&lt;vector&lt;double&gt;&gt; 作为返回类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
  • 2011-12-18
  • 2018-03-09
相关资源
最近更新 更多