C++ Lambda Functions: Modifying Vectors vs Returning Values

Listen to this Post

In C++, lambda functions provide a concise way to define anonymous functions. A key consideration is whether the lambda modifies the original data or returns a new value.

Example Code:

include <iostream>
include <vector>
include <algorithm>

int main() {
std::vector<int> v = {1, 2, 3, 4, 5};

// Lambda that returns modified value (does NOT modify original vector)
auto multiplyBy2 = [](int n) { return n  2; };
std::transform(v.begin(), v.end(), v.begin(), multiplyBy2);

// Output: 2 4 6 8 10
for (int num : v) {
std::cout << num << " ";
}
return 0;
}

Answer: A) Yes (Prints 2 4 6 8 10)
– `std::transform` applies the lambda to each element and stores the result back in the vector.

You Should Know:

1. Modifying vs. Non-Modifying Lambdas

  • Modifying (Pass by Reference):
    auto modifyInPlace = [](int &n) { n = 2; };
    std::for_each(v.begin(), v.end(), modifyInPlace); // Original vector changed
    
  • Non-Modifying (Pass by Value):
    auto getSquare = [](int n) { return n  n; }; // Returns new value
    

2. Key C++ Commands

  • std::transform: Applies a function to a range and stores results.
  • std::for_each: Executes a function on each element (can modify if passed by reference).

3. Linux Command Analogy

– `sed` (Stream Editor): Modifies text in-place (like pass-by-reference).

sed -i 's/old/new/g' file.txt  Modifies file directly

awk: Processes and returns new output (like pass-by-value).

awk '{print $12}' file.txt  Outputs transformed data

4. Windows PowerShell Equivalent

 Modifying an array in-place
$array = 1..5
$array = $array | ForEach-Object { $_  2 }  Returns new array

What Undercode Say:

  • Always check whether a lambda modifies data or returns a new value.
  • Use `std::transform` for transformations and `std::for_each` for in-place changes.
  • In Linux, tools like `sed` and `awk` follow similar paradigms.

Expected Output:

2 4 6 8 10 

References:

Reported By: Mohamed Khabou – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 TelegramFeatured Image