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/