title: How to pass one element of a vector to a function as reference in C++?
body: <p>I'm trying to manipulate the values of a 0-initialized vector in a loop in C++.
  However when I print out the values of the vector it shows only sensible values inside the "myFunction". Outside of it the values did not change.
  Here is a sketch of my example:</p>
  
  <pre><code>vector&lt;float&gt; meanDistances(numDescriptors);  
  
  for (int i = 0; i &lt; numDescriptors, i++)  
  {
      myFunction(arg1, arg2,...,meanDistances[i]));
      cout &lt;&lt; "meanDistance OUTSIDE myFunction: " &lt;&lt; meanDistances[i] &lt;&lt; endl;
  }
  </code></pre>
  
  <p>This is how "myFunction" looks like:</p>
  
  <pre><code>void myFunction(arg1, arg2, ..., float &amp; meanDistance)
  {
      meanDistance = someFloatNumber;
      cout &lt;&lt; "meanDistance INSIDE myFunction: " &lt;&lt; meanDistance &lt;&lt; endl;
  }
  </code></pre>
  
  <p>How can I pass single elements of my vector as reference to a function?</p>
  
  <p>Edit:<br>
  here is some more code  </p>
  
  <pre><code>boost::thread_group threadGroup;
  for (int i = 0; i &lt; numDescs ; i++ )
  {
      int threadIdx = i % numThreads;
  
      vecHists[i].convertTo(vecHists[i], CV_32F);
      threadGroup.create_thread(boost::bind( &amp;myFunction, vecHists[i],vecHists[i],vecDistanceMats[threadIdx], meanDistances[i]));
  
  
  
      sleep(1);
  
      if(threadIdx == numThreads-1 || i == numDescs-1)
      {
          threadGroup.join_all();
          for (int j = 0; j &lt; numThreads ; j++)
          {
              sumDistanceMats += vecDistanceMats[j];
          }
      }
  }
  for (int i = 0; i &lt; numDescs ; i++ )
  {
    cout &lt;&lt; "meanDistances OUTSIDE myFunction after all threads are joined again: " &lt;&lt; meanDistances[i] &lt;&lt; endl;
  }
  </code></pre>
  
  <p>Edit2:<br>
  It turns out that the problem in this function rather lies in the functionality of <code>boost::threadGroup</code>. If I exchange the <code>vector&lt;float&gt; meanDistances</code> vector by a vector of 1x1 dim opencv Mats <code>vector&lt;cv::Mat&gt; meanDistances</code> everything is working fine.<br>
  Of course I'm also modifying <code>myFunction</code> accordingly:  </p>
  
  <pre><code>void myFunction(arg1, arg2, ..., Mat&amp; matMeanDistance)
  {
      meanDistance.at&lt;float&gt;(0,0) = someFloatNumber;
      cout &lt;&lt; "meanDistance INSIDE myFunction: " &lt;&lt; matMeanDistance.at&lt;float&gt;(0,0) &lt;&lt; endl;
  }
  </code></pre>
  
  <p>So somehow <code>boost::threadGroup</code> treats vectors of <code>float</code>s different than vectors of <code>cv::Mat</code></p>