I have written this program, which sorts some ints using a functor:
#include<iostream>
#include<list>
#include<set>
using namespace std;
struct IntSorter
{
unsigned int comparisons;
IntSorter()
{
std::cout << "new intsorter" << std::endl;
comparisons = 0;
}
bool operator() (const int &a, const int &b)
{
std::cout << "c is " << comparisons << std::endl;
++comparisons;
std::cout << "c is now " << comparisons << std::endl;
return a<b;
}
};
int main(int argc, char *argv[])
{
list<int> my_list;
my_list.push_back(4);
my_list.push_back(3);
my_list.push_back(5);
my_list.push_back(1);
IntSorter s;
my_list.sort(s);
for (list<int>::iterator it=my_list.begin(); it!=my_list.end(); it++)
{
std::cout << *it << std::endl;
}
return 0;
}
The sorting works fine, but the part counting the number of comparisons gives a result I didn't expect:
./prog -a -b -c -d
new intsorter
c is 0
c is now 1
c is 0
c is now 1
c is 0
c is now 1
c is 1
c is now 2
c is 2
c is now 3
1
3
4
5
I was thinking the structure would be reused, counting and storing the number of comparisons. However, it appears to copy it, or some other behaviour as the numbers printed out go 1,1,1,2,3, instead of 1,2,3,4,5. What am I doing wrong?