Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To make use of the <em>range-based for-loop</em> you have to provide either <code>begin()</code> and <code>end()</code> member functions or overload the non-member <code>begin()</code> and <code>end()</code> functions. In the latter case, you can wrap your range in a <code>std::pair</code> and overload <code>begin()</code> and <code>end()</code> for those:</p> <pre><code> namespace std { template &lt;typename T&gt; T* begin(std::pair&lt;T*, T*&gt; const&amp; p) { return p.first; } template &lt;typename T&gt; T* end(std::pair&lt;T*, T*&gt; const&amp; p) { return p.second; } } </code></pre> <p>Now you can use the for-loop like this:</p> <pre><code> for (auto&amp;&amp; i : std::make_pair(array, array + size)) cout &lt;&lt; i &lt;&lt; endl; </code></pre> <p>Note, that the non-member <code>begin()</code> and <code>end()</code> functions have to be overloaded in the <code>std</code> namespace here, because <code>pair</code> also resides in namespace <code>std</code>. If you don't feel like tampering with the standard namespace, you can simply create your own tiny pair class and overload <code>begin()</code> and <code>end()</code> in your namespace.</p> <p>Or, create a thin wrapper around your dynamically allocated array and provide <code>begin()</code> and <code>end()</code> member functions:</p> <pre><code> template &lt;typename T&gt; 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 &lt;typename T&gt; wrapped_array&lt;T&gt; wrap_array(T* first, std::ptrdiff_t size) noexcept { return {first, size}; } </code></pre> <p>And your call site looks like this:</p> <pre><code> for (auto&amp;&amp; i : wrap_array(array, size)) std::cout &lt;&lt; i &lt;&lt; std::endl; </code></pre> <p><a href="http://liveworkspace.org/code/3rzx8X$3" rel="noreferrer">Example</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload