Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is how I would approach it:</p> <p>Pretend you have a <code>vector&lt;SomeValue&gt;</code> that is sorted. This vector is accessible using <code>someFunction(index)</code>.</p> <p>Now, <a href="http://en.wikipedia.org/wiki/Binary_search#algorithm" rel="nofollow">look at this</a>. That is pseudocode for the binary search. Continuing with the thought process above, replace <code>A[imid]</code> with <code>someFunction(imid)</code> and make <code>key</code> a <code>SomeValue</code>. Make sure <code>SomeValue</code> has a valid <code>operator &lt;</code> (or a comparator function that you use in place of it).</p> <p>This will of course only work if <code>someFunction(x) &lt; someFunction(x + 1)</code> for all <code>x</code>. You have stated this to be true, so it should be good.</p> <p>I would suggest using the iterative approach because both have the same asymptotic runtime, and the iterative version makes it easier to report a key that was not found, and tends to use less memory.</p> <p><strong>EDIT</strong> I am unaware of a simple way to do it using the <code>std</code> stuff. As you mentioned above, <code>int</code> wouldn't work as an iterator, and all of the functions that you would probably want to use take iterators. <em>Technically</em> though, the iterators in these functions are templated types, so you write your own <code>IntIter</code> class or something like that. Using <code>std::lower_bound</code> would need the <code>operator *()</code>, <code>operator ++()</code>, and <code>operator +(int)</code>. <code>operator *()</code> would probably return <code>someFunction(n)</code>, where <code>n</code> is the int value associated with the <code>IntIter</code>. However, <strong><em>I don't know if this would actually work</em></strong>, and it would probably take more time and coding. You should look at <a href="http://www.cplusplus.com/reference/algorithm/lower_bound/" rel="nofollow"><code>std::lower_bound</code></a> and <a href="http://www.cplusplus.com/reference/iterator/advance/" rel="nofollow"><code>std::advance</code></a> (called in <code>lower_bound</code>) if you want to take this approach.</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. 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