title: Shortest solution to permute the elements of a std::vector using stl
body: <p>Assume that you have an <code>std::vector&lt;T&gt;</code> of some type <code>T</code> and a selection of indices <code>std::vector&lt;int&gt;</code> of this vector. Now I'm looking for a function <code>permute(const std::vector&lt;T&gt;&amp; vector, const std::vector&lt;int&gt;&amp; indices)</code>, that returns the permuted vector with respect to the given indices.</p>
  
  <p>The problem is easily solved by writing a short function like depicted below:</p>
  
  <pre><code>template&lt;typename T&gt;
  std::vector&lt;T&gt; permute(const std::vector&lt;T&gt;&amp; matrix, const std::vector&lt;int&gt;&amp; indices) {
      std::vector&lt;T&gt; ret;
      for (auto p : indices) {
          ret.push_back(matrix[p]);
      }
      return ret;
  }
  
  int main(int, char**) {
      std::vector&lt;int&gt; perm{ 1,2,0 };
      std::vector&lt;std::vector&lt;double&gt;&gt; matrix = { {1.,2.,3.},{4.,5.,6.},{7.,8.,9.} };
      auto matrixPerm=permute(matrix, perm);
      std::cout &lt;&lt; matrixPerm[0][0] &lt;&lt; " == " &lt;&lt; matrix[1][0] &lt;&lt; std::endl;
      std::cout &lt;&lt; matrixPerm[1][0] &lt;&lt; " == " &lt;&lt; matrix[2][0] &lt;&lt; std::endl;
      std::cout &lt;&lt; matrixPerm[2][0] &lt;&lt; " == " &lt;&lt; matrix[0][0] &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>I'm now wondering what might be most elegant version of this program, if we can use STL or even the Boost libraries. In STL for example we have <code>shuffle()</code>, but we cannot say in what way to shuffle. </p>
  
  <p>Does anyone now, how to shorten the function?</p>
  
  <h1>Solution using <code>std::transform()</code></h1>
  
  <pre><code>#include &lt;vector&gt;
  #include &lt;iostream&gt;
  #include &lt;iterator&gt;
  #include &lt;algorithm&gt;
  
  int main(int, char**) {
      std::vector&lt;int&gt; perm{ 1,2,0 };
      std::vector&lt;std::vector&lt;double&gt;&gt; matrix = { {1.,2.,3.},{4.,5.,6.},{7.,8.,9.} };
      std::vector&lt;std::vector&lt;double&gt;&gt; output;
      std::transform(perm.begin(), perm.end(), std::back_inserter(output), [&amp;](int i) { return matrix[i]; });
  
      std::cout &lt;&lt; output[0][0] &lt;&lt; " == " &lt;&lt; matrix[1][0] &lt;&lt; std::endl;
      std::cout &lt;&lt; output[1][0] &lt;&lt; " == " &lt;&lt; matrix[2][0] &lt;&lt; std::endl;
      std::cout &lt;&lt; output[2][0] &lt;&lt; " == " &lt;&lt; matrix[0][0] &lt;&lt; std::endl;
  }
  </code></pre>