gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:14:50 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com