Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I mostly agree with Earwicker in that you can define a range. Now, I am in favor of implementing operators with the real meaning (do what basic types do: two ranges compare equal if both ranges ARE equal). Then you can use the third map parameter to pass it a comparison functor (or function) that solves your particular problem with this map.</p> <pre><code>// Generic range, can be parametrized for any type (double, float, int...) template&lt; typename T &gt; class range { public: typedef T value_type; range( T const &amp; center ) : min_( center ), max_( center ) {} range( T const &amp; min, T const &amp; max ) : min_( min ), max_( max ) {} T min() const { return min_; } T max() const { return max_; } private: T min_; T max_; }; // Detection of outside of range to the left (smaller values): // // a range lhs is left (smaller) of another range if both lhs.min() and lhs.max() // are smaller than rhs.min(). template &lt;typename T&gt; struct left_of_range : public std::binary_function&lt; range&lt;T&gt;, range&lt;T&gt;, bool &gt; { bool operator()( range&lt;T&gt; const &amp; lhs, range&lt;T&gt; const &amp; rhs ) const { return lhs.min() &lt; rhs.min() &amp;&amp; lhs.max() &lt;= rhs.min(); } }; int main() { typedef std::map&lt; range&lt;double&gt;, std::string, left_of_range&lt;double&gt; &gt; map_type; map_type integer; // integer part of a decimal number: integer[ range&lt;double&gt;( 0.0, 1.0 ) ] = "zero"; integer[ range&lt;double&gt;( 1.0, 2.0 ) ] = "one"; integer[ range&lt;double&gt;( 2.0, 3.0 ) ] = "two"; // ... std::cout &lt;&lt; integer[ range&lt;double&gt;( 0.5 ) ] &lt;&lt; std::endl; // zero std::cout &lt;&lt; integer[ range&lt;double&gt;( 1.0 ) ] &lt;&lt; std::endl; // one std::cout &lt;&lt; integer[ 1.5 ] &lt;&lt; std::endl; // one, again, implicit conversion kicks in } </code></pre> <p>You must be careful with equality and comparisons among double values. Different ways of getting to the same value (in the real world) can yield slightly different floating point results.</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