-1

I am trying to use the function adjacent_difference from the numeric library on the second element of each entry of a vector of pairs (vector<pair<double,double>>). How can I do it?

Update: here's my code so far (obviously wrong xD):

vector <pair<double,double>> initvalues; //receives pairs with the structure (174.386, 10)
for(int i = 0; i < 10; ++i)
{
  initvalues.push_back(make_pair(i, 2+i));
}
vector <pair<double,double>> result(initvalues.size()-1);
adjacent_difference((initvalues.second).begin(),(initvalues.second).end(), (result.second).begin());

initvalues is my main vector that allocates pairs of valus with the structure (174.386, 10) as example. result is the output I want and it will store the first entry of the initvalues vector in the first pair entry and the adjacent_difference in the second entry of the pair.

However, I obtain the following output in the terminal compiling the code I've pasted in here:

    stack.C: In function ‘int main()’:
stack.C:16:35: error: ‘class std::vector<std::pair<double, double> >’ has no member named ‘second’
   16 |   adjacent_difference((initvalues.second).begin(), (initvalues.second).end(), (result.second).begin());
      |                                   ^~~~~~
stack.C:16:64: error: ‘class std::vector<std::pair<double, double> >’ has no member named ‘second’
   16 | adjacent_difference((initvalues.second).begin(), (initvalues.second).end(), (result.second).begin());
      |                                                              ^~~~~~

stack.C:16:87: error: ‘class std::vector<std::pair<double, double> >’ has no member named ‘second’
   16 | nitvalues.second).begin(), (initvalues.second).end(), (result.second).begin());
      |                                                               ^~~~~~
David Buck
  • 3,752
  • 35
  • 31
  • 35
  • That's much better, thanks. Voting to reopen. Minor point, the comment about "*... the structure (174.386, 10) as example ...*" doesn't seem to apply, since you are creating the values `(0, 2), (1, 3), ...` in your example now. – cigien Nov 14 '20 at 11:01

1 Answers1

1

If I understand you, this is what you want:

vector<pair<double, double>> initvalues; 
for (int i = 0; i < 10; ++i) {
    initvalues.push_back(make_pair(i, 2 + i));
}
vector<pair<double, double>> result;
result.reserve(initvalues.size());

adjacent_difference(initvalues.begin(), initvalues.end(),
    std::back_inserter(result),
    [](const auto& l, const auto& r) {
        return std::pair<double, double>{l.first, l.second - r.second};
    });

This gives you:

initValues = {0, 2} {1, 3} {2, 4} {3, 5} {4, 6} {5, 7} {6, 8} {7, 9} {8, 10} {9, 11} 
result     = {0, 2} {1, 1} {2, 1} {3, 1} {4, 1} {5, 1} {6, 1} {7, 1} {8, 1} {9, 1}
bolov
  • 72,283
  • 15
  • 145
  • 224