I wanted to get the index of the value(s) inside std
algorithm's lambda function. So that, I can perform computation on the values based on the index. I am able to get an index with for_each
function. However, I am not able to do so for std::adjacent_difference
. Can you help me understand why I am not able to extract the index in other algorithms that use binary op? My attempt is to try in a generic fashion that work on a parallel (thrust) setting as well. So, did not seek a method of static
count'ing.
//~~~START:Mon, 04-Oct-2021, 13:03:46 IST
//~~~Author:Rajesh Pandian M | mrprajesh.co.in
#include <bits/stdc++.h>
void print(const auto &data){
std::copy(data.begin(),data.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
}
int main(int argc, char* argv[]){
std::vector<int> data={0,2,3,5,10,11};
std::for_each(data.begin(), data.end(), [&data](int const& value) {
int idx = &value - &data[0];
std::cout<< "idx: " << idx << '\n';
});
print(data);
std::vector<int> result(data.size());
std::adjacent_difference(data.begin(), data.end(), result.begin(),
[&data]( const int& value2, const int& value1) {
int idx = &value2 - &data[0];
std::cout<< "idx: " << idx << '\n';
return value2-value1; //Some expression involving index, values[1,2]
});
print(result);
return 0;
}
Outputs:
idx: 0
idx: 1
idx: 2
idx: 3
idx: 4
idx: 5
0 2 3 5 10 11
idx: -102822055
idx: -102822055
idx: -102822055
idx: -102822055
idx: -102822055
0 2 1 2 5 1