title: Obtaining smallest key in a std::map
body: <p>I need to get the smallest element in a <code>std::map</code>. I'm aware that there is plenty of documentation available; however, I can't seem to get any to work.</p>
  
  <p>I have two maps, <code>bid</code> and <code>ask</code>, both of which are properties of the <code>Book</code> class. Each is a map of queues. Each of these queues hold <code>Order</code> objects (which have various properties like <code>price</code>, <code>volume</code>, etc.). I have a member function <code>update</code> which obtains the best bid, best ask, and the spread:</p>
  
  <pre><code>void update(void)
  {
    unsigned long long highest_bid, lowest_ask = 0;
  
    for (std::map&lt;unsigned long long, queue&lt;Order&gt;&gt;::iterator it = this-&gt;bid.begin(); it != this-&gt;bid.end(); ++it)
    { 
      highest_bid = it-&gt;first;
    }
  
    // best ask code here
  
    this-&gt;bestBid = highest_bid;
    this-&gt;bestAsk = lowest_ask;
    this-&gt;spread = labs(this-&gt;bestAsk - this-&gt;bestBid);
  }
  </code></pre>
  
  <p>Where the ask code is, I've tried the following:</p>
  
  <pre><code>lowest_ask = this-&gt;ask.begin()-&gt;first;
  </code></pre>
  
  <p>This compiles, but when I debug it throws an assertion failure (which I've read up on other questions here and can't seem to understand):</p>
  
  <pre><code>Expression: map/set iterator not dereferencable
  </code></pre>
  
  <p>I've tried reverse iteration:</p>
  
  <pre><code>for(std::map&lt;unsigned long long, queue&lt;Order&gt;&gt;::reverse_iterator rit = this-&gt;ask.rbegin(); rit != this-&gt;ask.rend(); ++rit)
  {
    lowest_ask = rit-&gt;first;
  }
  </code></pre>
  
  <p>Which compiles and debugs fine, but <code>lowest_ask</code> is always 0, which is wrong. When I step through it in the debugger it doesn't stop until it reaches zero.</p>
  
  <p>I've tried swapping the iterators around:</p>
  
  <pre><code>for(std::map&lt;unsigned long long, queue&lt;Order&gt;&gt;::reverse_iterator rit = this-&gt;ask.rend(); rit != this-&gt;ask.rbegin(); ++rit)
  {
    lowest_ask = rit-&gt;first;
  }
  </code></pre>
  
  <p>This compiled fine, but once again threw the debug assertion failure.</p>
  
  <p>I could continue on and on on what I've tried, but this question is already over-complicated. I just don't understand why I can't just do what I did at the start (<code>lowest_ask = this-&gt;ask.begin()-&gt;first</code>).</p>
  
  <p>Thank you very much in advance.</p>