Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You should always prefer container classes over raw arrays. But, if you absolutely must use an array, you can certainly accomplish swapping without resorting to dynamically allocating the temporary array. Use templates to statically determine the type and size of the arrays being passed into the swap function.</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;string&gt; template&lt;typename T, size_t N&gt; void swap_arrays( T(&amp;left)[N], T(&amp;right)[N] ) { T temp[N]; // copy left to temp std::copy( std::begin(left), std::end(left), std::begin(temp) ); // copy right to left std::copy( std::begin(right), std::end(right), std::begin(left) ); // copy temp to right std::copy( std::begin(temp), std::end(temp), std::begin(right) ); } template&lt;typename T, size_t N&gt; void swap_and_print( T(&amp;left)[N], T(&amp;right)[N] ) { std::cout &lt;&lt; "\nBefore swapping: \n"; std::cout &lt;&lt; " Left:"; std::for_each( std::begin(left), std::end(left), []( T const&amp; t ) { std::cout &lt;&lt; " " &lt;&lt; t; } ); std::cout &lt;&lt; "\n Right:"; std::for_each( std::begin(right), std::end(right), []( T const&amp; t ) { std::cout &lt;&lt; " " &lt;&lt; t; } ); swap_arrays( left, right ); std::cout &lt;&lt; "\nAfter swapping: \n"; std::cout &lt;&lt; " Left:"; std::for_each( std::begin(left), std::end(left), []( T const&amp; t ) { std::cout &lt;&lt; " " &lt;&lt; t; } ); std::cout &lt;&lt; "\n Right:"; std::for_each( std::begin(right), std::end(right), []( T const&amp; t ) { std::cout &lt;&lt; " " &lt;&lt; t; } ); } int main() { int foo1[] = {1,2,3,4,5}; int bar1[] = {6,7,8,9,10}; swap_and_print( foo1, bar1 ); char foo2[] = "James"; char bar2[] = "Sarah"; swap_and_print( foo2, bar2 ); } </code></pre> <p>Output:</p> <pre><code>Before swapping: Left: 1 2 3 4 5 Right: 6 7 8 9 10 After swapping: Left: 6 7 8 9 10 Right: 1 2 3 4 5 Before swapping: Left: J a m e s � Right: S a r a h � After swapping: Left: S a r a h � Right: J a m e s � </code></pre> <p><em>Note:</em> The weird character at the end of the second example is because the inputs are <code>char</code> arrays that include the terminating null character; and what you're seeing is its visual representation (since the code is printing it out as a character).</p>
    singulars
    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. 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