ファンクターを使用していくつかの int をソートするこのプログラムを作成しました。
#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;
}
並べ替えは正常に機能しますが、比較の数をカウントする部分では、予期しない結果が得られます。
./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
私は構造が再利用され、比較の数を数えて保存すると思っていました。ただし、出力された数字が 1,2,3,4,5 ではなく 1,1,1,2,3 になるため、それをコピーするか、その他の動作をしているように見えます。私は何を間違っていますか?