我寫了這個程序,用一個仿函數這種種的一些整數:C++函數 - 意外的行爲?
#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,1,1,2,3而不是1,2,3,4,5。我究竟做錯了什麼?
而要證明這一點,你也可以的「這個」在運營商()以及輸出值。 – 2009-10-16 20:15:08
這是一個很好的觀點。 – 2009-10-16 20:33:52