Here are some examples of lambda captures:
[] Capture nothing
[&] Capture any referenced variable by reference
[=] Capture any referenced variable by making a copy
[=, &foo] Capture any referenced variable by making a copy, but
capture variable foo by reference
[bar] Capture bar by making a copy; don't copy anything else
[this] Capture the this pointer of the enclosing class
Hence if pi in your example is a local variable (not a macro or a global variable) you can not let [] but use [pi] to capture by copy (which is sane for a double):
std::transform(dataPhase.begin(), dataPhase.end(), dataPhase.begin(),
[pi](double v){return fmod(v, pi*1.00001); }
);
For your second example there is no built-in std::transform providing the index. I think the better solution is to keep your for loop.
If you really want to use lambda (as an exercise) you can use:
const int halfsize = int(length/2);
auto lambda=[&axis,halfsize](const int i){axis[i] = i - halfsize;};
for (size_t i=0; i < length; ++i)
{
lambda(i);
}
or
const int halfsize = int(length/2);
auto lambda=[halfsize](const int i){return i - halfsize;};
for (size_t i=0; i < length; ++i)
{
axis[i] = lambda(i);
}
It only depends on how you want to design your code.
Remark 1: it seems that you want to avoid "basic" for loops, however they are not necessary evil especially if you want to use OpenMP to gain some performances (simd or multi-threading). For instance
#pragma omp simd
for(auto& v_i :v) { // or worst std::transform
v_i = fmod(v_i, pi*1.00001);
}
is not supported and will not compile.
However
#pragma omp simd
for (size_t i=0; i < dataPhase.size(); ++i)
{
dataPhase[i] = fmod(dataPhase[i], pi*1.00001);
}
can be compiled with g++ -fopenmp ... with potential perf gain if simd can be used. Concerning multi-threading, one can argue that there is a coming support for parallel execution of the STL algorithms, but this is only for C++17.
Remark 2: not in C++ but in D language you have a foreach instruction that let you optionally include the index:
foreach (e; [4, 5, 6]) { writeln(e); }
// 4 5 6
but
foreach (i, e; [4, 5, 6]) { writeln(i, ":", e); }
// 0:4 1:5 2:6