2

I want to print the first 2 values where the next is doubled from the current value.

#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;

bool doubled (int x, int y) { return x*2 == y; }

int main()
{
  deque<int> di;
  deque<int>::iterator diiter;

  for (int i=0; i<=10; i+=2) di.insert(di.end(), i);

  for (diiter = di.begin(); diiter != di.end(); ++diiter)
    cout << *diiter << " ";
  cout << endl;

  diiter = adjacent_find(di.begin(), di.end(), doubled);
  if (diiter != di.end()) {
    cout << "found " << *diiter << " at " << distance(di.begin(), diiter)+1 
         << " and " << *(++diiter) << " at " << distance(di.begin(), diiter)+1 
         << endl;
  }
}

the output is

0 2 4 6 8 10 
found 4 at 3 and 4 at 2

not what I expected, which should be:

0 2 4 6 8 10 
found 2 at 2 and 4 at 3

What's wrong with my code? I don't understand how the second position is decremented from the first one when I actually incremented it. Thanks for all help.

Stack Overeem
  • 835
  • 1
  • 7
  • 5

1 Answers1

5

Your program is giving strange results because it does not take in to account the fact, that order of evaluation of arguments to a function(In this case operator <<) is Unspecified.

My Answer here, explains the problem in detail & should be a good read.

You need to cout them on separate statements.

 cout << "found " << *diiter;
 cout << " at " << distance(di.begin(), diiter)+1;
 cout << " and " << *(++diiter);
 cout << " at " << distance(di.begin(), diiter)+1;
 cout << endl;

This works well & outputs the correct/desired output.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • Is there a way to put them in just one line? I know putting them on separate lines would work but it looks ugly and I'm still not clear about order of evaluation being unspecified. could you give me more pointer about this? does it related to temporary variable involved (++diter)? – Stack Overeem Aug 16 '11 at 05:36
  • 1
    @Stack Overeem: Please refer the link to another Q I posted in the Answer, It explains the problem well in detail. – Alok Save Aug 16 '11 at 05:38
  • 1
    @Stack `++diiter` is indeed the problem. `diiter + 1` will [work](http://ideone.com/WsElA) but relies on the fact that it's a random-access iterator; you can use `std::next(diiter)` with C++0x instead (if not using C++0x you can roll your own `next`). – Luc Danton Aug 16 '11 at 05:39