Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This might do what you want. It uses <code>std::transform</code> internally, which basically does the whole work. The function I wrote is nothing more than a simple wrapper for containers (not working with C-style arrays, that would require some additional type traits):</p> <pre><code>#include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;type_traits&gt; // // Takes an iterable, applies a function to every element, // and returns a vector of the results // template &lt;typename T, typename Func&gt; auto map_container(const T&amp; iterable, Func&amp;&amp; func) -&gt; std::vector&lt;decltype(func(std::declval&lt;typename T::value_type&gt;()))&gt; { // Some convenience type definitions typedef decltype(func(std::declval&lt;typename T::value_type&gt;())) value_type; typedef std::vector&lt;value_type&gt; result_type; // Prepares an output vector of the appropriate size result_type res(iterable.size()); // Let std::transform apply `func` to all elements // (use perfect forwarding for the function object) std::transform( begin(iterable), end(iterable), res.begin(), std::forward&lt;Func&gt;(func) ); return res; } </code></pre> <p>However, notice that your lambda should take a reference to <code>const</code>, or better should take its argument by value in the case of <code>int</code>. </p> <p>Also, I renamed the function from <code>map</code> into <code>map_container</code>: it is a bad programming practice to reuse names of standard containers of the C++ Standard Library for functions, variables, or anything else in your program.</p> <p>For me, this gives the desired output:</p> <pre><code>#include &lt;iostream&gt; int main() { std::vector&lt;int&gt; intVector; intVector.push_back(1); intVector.push_back(2); auto v = map_container(intVector, [] (int value) { return value + 1; }); for (int i : v) { std::cout &lt;&lt; i &lt;&lt; " "; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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