如何在此代码片段中创建 begin() 指针
How is the begin() pointer created in this code snippet?
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];
如果向量不为空,则返回存储在指针中的第一个元素的地址
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 调用'begin(int [n])'没有匹配函数
- 链接到自行创建的dll失败
- 如何在此代码片段中创建 begin() 指针
- 是否可以使用 begin() 和 end() 创建 std::array?