patterncppMinor
Iterating over unequal unordered pairs in one collection
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
Is there a better way to do the task?
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
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.
#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.