基于范围动态数组的循环? [英] Range-based for loop on a dynamic array?
问题描述
有一个基于范围与语法循环:
There is a range-based for loop with the syntax:
for(auto& i : array)
它的工作原理与常数组但不与基于指针动态的,像
It works with constant arrays but not with pointer based dynamic ones, like
int *array = new int[size];
for(auto& i : array)
cout<< i << endl;
它给出错误和警告有关替代的故障,例如:
It gives errors and warnings about failure of substitution, for instance:
错误] C:\\用户\\ Siegfred \\文档\\ C-免费的\\ Temp \\ Untitled2.cpp:16:16:错误:呼叫没有匹配功能开头为(int *&安培;)
Error] C:\Users\Siegfred\Documents\C-Free\Temp\Untitled2.cpp:16:16: error: no matching function for call to 'begin(int*&)'
我如何使用这个新的语法与动态数组?
How do I use this new syntax with dynamic arrays?
推荐答案
要使用的的基于范围的for循环的你必须提供任何开始()
和端()
成员函数或超负荷非会员开始()
和端()
功能。
在后一种情况下,你可以用你的范围在的std ::对
和超载开始()
和端()
对于那些:
To make use of the range-based for-loop you have to provide either begin()
and end()
member functions or overload the non-member begin()
and end()
functions.
In the latter case, you can wrap your range in a std::pair
and overload begin()
and end()
for those:
namespace std {
template <typename T> T* begin(std::pair<T*, T*> const& p)
{ return p.first; }
template <typename T> T* end(std::pair<T*, T*> const& p)
{ return p.second; }
}
现在,您可以使用for循环是这样的:
Now you can use the for-loop like this:
for (auto&& i : std::make_pair(array, array + size))
cout << i << endl;
请注意,该非会员开始()
和端()
功能都在超负荷 STD
命名空间在这里,因为对
还驻留在命名空间 STD
。如果你不喜欢的标准命名空间篡改,您可以简单地创建自己的小对类和过载开始()
和端()
在您的命名空间。
Note, that the non-member begin()
and end()
functions have to be overloaded in the std
namespace here, because pair
also resides in namespace std
. If you don't feel like tampering with the standard namespace, you can simply create your own tiny pair class and overload begin()
and end()
in your namespace.
或者,创建了简单包装的您的动态分配的数组,并提供开始()
和端()
成员功能:
Or, create a thin wrapper around your dynamically allocated array and provide begin()
and end()
member functions:
template <typename T>
struct wrapped_array {
wrapped_array(T* first, T* last) : begin_ {first}, end_ {last} {}
wrapped_array(T* first, std::ptrdiff_t size)
: wrapped_array {first, first + size} {}
T* begin() const noexcept { return begin_; }
T* end() const noexcept { return end_; }
T* begin_;
T* end_;
};
template <typename T>
wrapped_array<T> wrap_array(T* first, std::ptrdiff_t size) noexcept
{ return {first, size}; }
和您的电话的网站看起来是这样的:
And your call site looks like this:
for (auto&& i : wrap_array(array, size))
std::cout << i << std::endl;
这篇关于基于范围动态数组的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!