Note that there are some explanatory texts on larger screens.

plurals
  1. POIndexing an std::vector with a negative index
    primarykey
    data
    text
    <p>I tried to index a <code>vector</code> using a negative index. The <code>vector::at()</code> member function checks whether the specified index is within the bounds of the vector, and if this does not occur, an <code>out_of_range</code> exception is thrown.</p> <pre><code>vector&lt;float&gt; array; // sample vector array.push_back(0.123); array.push_back(1.234); array.push_back(2.345); array.push_back(3.456); array.push_back(4.567); int index = -1; float f = array.at(index); cout &lt;&lt; f &lt;&lt; endl; </code></pre> <p>The signature of <code>vector::at()</code> member function requires that the specified parameter is of <code>vector&lt;T&gt;::size_type</code> type, and this type is <code>unsigned int</code> for the vector, so the compiler should perform an implicit conversion from <code>int</code> (the type of the <code>index</code> variable) to <code>unsigned int</code>. Since the <code>index</code> value is <code>-1</code> in the above example, the implicitly converted <code>index</code> is <code>4294967295</code> (that is the max value of the <code>unsigned int</code> type): this value is passed to <code>vector::at()</code> member function, which throws an <code>out_of_range</code> exception.</p> <p>In other words, this exception is not thrown because the <code>vector::at()</code> member function sees that the <code>index</code> is less than zero, but rather because the implicitly converted <code>index</code> is greater than the current size of the <code>vector</code>. Is this a correct explanation?</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.
 

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