Q:

Compare a set of two integers inside of a vector over and over while iterating through it

I have a vector of integers and i want to keep comparing each pair until all the integers have been compared. I want to find the absolute difference between the pair. For example:
30
25
65
183
83
22

30 and 25 are compared, then 65 and 183 are compared, then 83 and 22, and so on. I want to find the absolute difference of each comparison. The numbers are all random so it will have to find the bigger integer in the pair and subtract it from the smallest. How would I go about doing this?

A:

Try to use iterators over array indexing — for large sets you will see a difference.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>

int main()
{
  std::vector <int> xs = { 30, 25, 65, 183, 83, 22, -3 };
  std::vector <int> ds;

  auto print = [&]()
  {
    for (int d : ds)
      std::cout << d << " ";
    std::cout << "\n";
  };

  // method one (two-pass using standard algorithms)
  {
    std::adjacent_difference( begin(xs), end(xs), std::back_inserter( ds ), 
      []( int a, int b ) { return std::abs( b - a ); } 
    );
    bool b = false;
    ds.erase( std::remove_if( begin(ds), end(ds), [&b]( auto foo ) { return b = !b; } ), end(ds) );
  }
  print();

  // method two (one-pass for random access iterators, two-pass for sequential iterators)
  ds.clear();
  {
    auto a = begin(xs);
    auto b = next(a);
    auto n = std::distance( begin(xs), end(xs) ) / 2;
    while (n--)
    {
      ds.emplace_back( std::abs( *b - *a ) );
      a = next(b);
      b = next(a);
    }
  }
  print();

  // method three (one-pass for sequential iterators)
  ds.clear();
  {
    auto a = begin(xs);
    auto b = next(a);
    while (a != end(xs) and b != end(xs))
    {
      ds.emplace_back( std::abs( *b - *a ) );
      a = next( b );
      b = next( a );
    }
  }
  print();
}

Method one just uses standard algorithms, works well, and is easy to read. It always makes two passes and has double memory requirement than the other two algorithms. 
Method two is the most efficient given you have random access iterators. It makes one pass and only uses as much memory as needed. You can tweak that memory requirement with a simple ds.reserve( n ) and a simple assign, assuming ds is also accessed via random access iterator.
Method three is a variation that assumes nothing about your input iterators and still uses a single pass. (It might still fail on stream iterators unless you memoize some data... LOL, thanks C++.)

