Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>vec.begin()</code> and <code>vec.end()</code> do not return the first and last elements of the <code>vector</code>. They actually return what is known as an <em>iterator</em>. An iterator behaves very much like a pointer to the elements. If you have an iterator <code>i</code> that you initialised with <code>vec.begin()</code>, you can get a pointer to the second element in the vector just by doing <code>i++</code> - the same as you would if you had a point to the first element in an array. Likewise you can do <code>i--</code> to go backwards. For some iterators (known as random access iterators), you can even do <code>i + 5</code> to get an iterator to the 5th element after <code>i</code>.</p> <p>This is how the algorithm accesses the container. It knows that all of the elements that it should be sorting are between <code>begin()</code> and <code>end()</code>. It navigates around the elements by doing simple iterator operations. It can then modify the elements by doing <code>*i</code>, which gives the algorithm a reference to the element that <code>i</code> is pointing at. For example, if <code>i</code> is set to <code>vec.begin()</code>, and you do <code>*i = 5;</code>, you will change the value of the first element of <code>vec</code>.</p> <p>This approach allows you to pass only <em>part</em> of a <code>vector</code> to be sorted. Let's say you only wanted to sort the first 5 elements of your <code>vector</code>. You could do:</p> <pre><code>std::sort(vec.begin(), vec.begin() + 5); </code></pre> <p>This is very powerful. Since iterators behave very much like pointers, you can actually pass plain old pointers too. Let's say you have an array <code>int array[] = {4, 3, 2, 5, 1};</code>, you could easily call <code>std::sort(array, array + 5)</code> (because the name of an array will decay to a pointer to its first element).</p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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