我有一个指针“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)){
}
模板内容引入了 begin
和 end
的适当定义,这是范围 for
循环所需要的。
关于c++ - 您可以将指针转换为数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43256092/