HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Iterating over unequal unordered pairs in one collection

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pairsunorderediteratingcollectionoveroneunequal

Problem

This code kinda hurts my feelings -- everything else in my code is done in neat one-liners, exploiting algorithms and, sometimes boost::bind, except for this piece. To say nothing about awkward if(b!=a).

Is there a better way to do the task?

#include 
#include 
using namespace std;

int main()
{
    int arr[] = {1,2,3,4,5,6};
    list lst(arr,arr+sizeof(arr)/sizeof(int));

    for(list::iterator a = lst.begin(); a != lst.end();a++)
    {
            for(list::iterator b = a; b != lst.end(); b++)
                    if(b != a) cout << " ("<<*a<<","<<*b<<")";
            cout << "\n";
    }
    return 0;
}

Solution

Also not really pretty, but perhaps a start

#include 
#include 
#include 
using namespace std;

int main()
{
    list lst = {1,2,3,4,5,6};

    auto a = lst.cbegin();
    int first = *a;
    auto output_pairs = [&first](const int second){ cout << " ("<<first<<','<<second<<')'; };
    while(++a != lst.cend())
    {
        for_each(a, lst.cend(), output_pairs);
        cout << '\n';
        first = *a;
    }
    cout << flush;
}


It's C++0x because I was too lazy to write a functor for that lambda and I don't know the Boost.Lambda syntax off the top of my head.

Code Snippets

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

int main()
{
    list<int> lst = {1,2,3,4,5,6};

    auto a = lst.cbegin();
    int first = *a;
    auto output_pairs = [&first](const int second){ cout << " ("<<first<<','<<second<<')'; };
    while(++a != lst.cend())
    {
        for_each(a, lst.cend(), output_pairs);
        cout << '\n';
        first = *a;
    }
    cout << flush;
}

Context

StackExchange Code Review Q#3243, answer score: 2

Revisions (0)

No revisions yet.