title: For C++ sort(), how to pass a parameter to custom compare function?
body: <p>I want to use the standard sort function for sorting points in respect to their distance of another point (e.g. their barycenter). </p>
  
  <p>I know I can write a custom compare function, but I don't know how to pass a parameter to it. I want to have it thread-safe, so I do not want to store the parameter at one central location. Is there a way how to pass additional parameters to a custom compare function?</p>
  
  <pre><code>// Here is a compare function without a parameter for sorting by the x-coordinate
  struct Point2fByXComparator {
      bool operator ()(Point2f const&amp; a, Point2f const&amp; b) {
          return a.x &gt; b.x;
      }
  };
  
  // Here is the outline of another comparator, which can be used to sort in respect
  // to another point. But I don't know how to pass this other point to the compare
  // function:
  struct Point2fInRespectToOtherPointComparator {
      bool operator ()(Point2f const&amp; a, Point2f const&amp; b) {
          float distanceA = distance(a, barycenter);
          float distanceB = distance(b, barycenter);
  
          return distanceA &gt; distanceB;
      }
  };
  
  std::vector&lt;Point2f&gt; vec = ...;
  
  Point2f barycenter(0, 0);
  for (int i = 0; i &lt; vec.size(); i++) {
      barycenter += vec[i];
  }
  barycenter *= (1.0/vec.size());
  
  // In the next line I would have to pass the barycenter to the compare function
  // so that I can use the barycenter for comparison. But I don't know how to do
  // this.
  sort(vec.begin(), vec.end(), Point2fInRespectToOtherPointComparator());
  </code></pre>