gpt4 book ai didi

c++ - 您可以将指针转换为数组吗?

转载 作者:行者123 更新时间:2023-11-30 00:45:28 24 4
gpt4 key购买 nike

我有一个指针“a”,它是 A* 类型。我现在在那个地址有 n 个 A 类型的对象,我想遍历它们。

我想将它转换为 A[n],这样我就可以使用 c++11 range-for 并编写 for (auto temp : a){...} .当然,我可以用经典for(int i=0; i<n; i++) {temp=a[i]; ...}但是 range-for 更干净。

最佳答案

合理的代码中,我会回避它。但是 C++ 允许你做出纯粹邪恶的行为。本着这种精神,我提供了一个解决方案:

以相当大的混淆为代价,您可以编写一些准备模板:

namespace std
{
template <typename T> T* begin(std::pair<T*, T*> const& a)
{
return a.first;
}

template <typename T> T* end(std::pair<T*, T*> const& a)
{
return a.second;
}
}

然后你可以这样写

for (auto&& i : std::make_pair(a, a + n)){

}

模板内容引入了 beginend 的适当定义,这是范围 for 循环所需要的。

关于c++ - 您可以将指针转换为数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43256092/

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