Closest element in std map when discarding values
Consider replacing the while loop with two for loops that increment lower and upper iterators till they have a suitable value - and only afterwards setting closest - it might be doing more operations but it is more cache friendly.

Or simply create a new map2 with only valid values (simply filtrate unwanted). 

Though, different situation have different preferred solutions - there is a trade-off which solution is better depending on number of undesirable values in map2 and relative sizes of map1 and map2.

I don't think that you can improve it beyond that, lest you have some extra knowledge you haven't shared. In certain cases, you might want to implement some completely different solutions that are not reliant on map.

About the code itself, there are just a few minor issues:


You don't take care of the case when lower_bound return an end, in this case program will crash or UB. Same problem inside the while scope.
There is no need to declare the four iterators outside the scope. Just declare them with auto when you instantiate them. Nobody cares to see std::map&lt;int,float&gt;::iterator.
replace setClosest with

  template&lt;typename MapItr&gt;
  auto getClosestMapIterator(const MapItr &amp;upper, const MapItr &amp; lower, int key ) -&gt; const MapItr&amp; 
  {
     return abs( upper-&gt;first - key ) &lt; abs( lower-&gt;first - key ) ? upper : lower;
  }


and adjust usage auto closest = getClosestMapIterator(upper, lower, key); Also you better use abs instead of fabs, as fabs is for floating point types, so you unnecessarily cast integers to double with fabs.
Inside while the line closest == upper ? upper++ : lower--; is confusing. Simply write if scope. Don't use the expression cond ? ret_on_true : ret_on_false for side-effects, only when you want to get the return value.