如何在此代码片段中创建 begin() 指针

How is the begin() pointer created in this code snippet?

本文关键字:begin 创建 指针 片段 代码      更新时间:2023-10-16
template<typename T>
T* begin(Vector<T>& x)
{
    return x.size() ? &x[0] : nullptr; // pointer to first element or nullptr
}

换句话说,编译器如何计算 return 语句,以及?:运算符在此确切示例中如何工作?

编辑*:我不明白x.size()部分。 返回x[0]元素还不够吗?

*从评论中移出

扭曲问题下方的所有评论(应该在答案部分!

begin()函数始终返回指向模板类型T的指针(即 T*(。问题是如果传递的std::vector<T>为空,它应该返回什么?显然nullptr

这意味着相等if-else版本为:

if(x.size())    // size(unsigend type) can be inplicity converted to bool: true for +ve numbers false for 0 and -ve numbers
  return &x[0]; // return the address of the first element
else
  return nullptr; // return pointer poiting to null

请记住,std::vector为成员提供std::vector::empty。使用它会非常直观。

if(x.empty()) 
  return nullptr; // if empty
else
  return &x[0];

或者像问题中一样,使用条件运算符:

return x.empty() ? nullptr : &x[0];

如果向量不为空,则返回存储在指针中的第一个元素的地址