c++ - 这段代码中的 begin() 指针是如何创建的?

标签 c++ pointers templates return conditional-operator

template<typename T>
T* begin(Vector<T>& x)
{
    return x.size() ? &x[0] : nullptr; // pointer to first element or nullptr
}

换句话说,编译器如何评估 return 语句以及 ?: operators 在这个具体示例中如何工作?

编辑*:我不明白 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提供成员(member) std::vector::empty .使用它会非常直观。

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

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

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

关于c++ - 这段代码中的 begin() 指针是如何创建的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57123662/

相关文章:

c++ - 通过 LevelDB 将 Protocol Buffer 序列化数据从 C++ 传递到 Python

c++ - C++ "Identifier not found"问题的非常简单的代码

pointers - 如何在 Go 中强制将参数作为指针传递?

c++ - 如何在编译时替换元组元素?

CSS子菜单悬停颜色问题

c++ - 如何获取文件信息?

c - 数组名称如何具有其地址以及其中的第一个元素?

c++ - 为什么链表中的数据在嵌套函数中发生更改/损坏?

c++ - 将参数转发到可变参数模板函数时如何添加参数值?

c++ - 为什么无法访问 new[]'d 数组的大小?