Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need a value to pass to <code>equal_range</code>, and the obvious thing to use is a pointer. The obvious way to get one is just to create an instance of <code>B</code> with the correct value of <code>attr_</code>, and write a comparator that involves only the value of <code>attr()</code>. I'm going to assume you already know how to do that since you managed to get the vector sorted ;-)</p> <p>Provided there are no null pointers in the vector you could do this instead:</p> <pre><code>struct FindAttr { unsigned int attr; FindAttr(unsigned int attr) : attr(attr) {} bool operator()(B *left, B *right) { unsigned int leftval = left ? left-&gt;attr() : attr; unsigned int rightval = right ? right-&gt;attr() : attr; return leftval &lt; rightval; } }; ... return equal_range(vec_.begin(), vec_.end(), nullptr, FindAttr(value)); </code></pre> <p>You could make that a lambda:</p> <pre><code>return equal_range(vec_.begin(), vec_.end(), nullptr, [=value](B *left, B *right) { unsigned int leftval = left ? left-&gt;attr() : attr; unsigned int rightval = right ? right-&gt;attr() : attr; return leftval &lt; rightval; }); </code></pre> <p>You can actually cut out the pointer altogether, to give what I think is the "cleanest" solution:</p> <pre><code>struct FindAttr { bool operator()(B *left, unsigned int rightval) { return left-&gt;attr() &lt; rightval; } bool operator()(unsigned int leftval, B *right) { return leftval &lt; right-&gt;attr(); } }; ... return equal_range(vec_.begin(), vec_.end(), value, FindAttr()); </code></pre> <p>AFAIK there's no direct equivalent to this with a lambda, since lambdas can only have one call signature. I suppose you could write a lambda that takes a <code>boost::variant</code> (or any type that implicitly converts from both <code>unsigned int</code> and from <code>B*</code>, and that remembers which one it was).</p>
 

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