看Effective STL Item21时遇到的小问题
以下是我看Scott Meyers 《Effective STL》Item21的时候,顺手写的例子程序以实验文章中corrupt container的方法。例子程序中用到了STL泛型算法algorithm中的for_each()函数,但偶然发现用Borland C++ Compiler 5.5编译时,不需要#include<algorithm>就可以编译运行通过;而MSVC6的编译器则很正常,一定需要#include<algorithm>才能编译成功。
哪位大虾知道其中奥妙因果,请不吝赐教。谢谢!
// Test demo according to Effective STL Item 21:
// Always have comparison function return 'false' for equal values.
//
// "... the set concludes that 10A and 10B are NOT equivalent,
// hence NOT the same, and it thus goes about inserting 10B into
// the container alongside 10A. Technically, this action yields
// undefined behavior, but the nearly universal outcome is that
// the set ends up with TWO copies of the value 10, and that means
// it's not a set any longer. By using less_equal as our comparison
// type, we've corrupted the container!"
// ---- Scott Meyers
#include <iostream> // cout
#include <set> // set
#include <functional> // less_equal
// In the case of Borland C++ Compiler 5.5 (BCB5/bcc32.exe),
// the demo still compiles even if we don't add this #include
// for 'for_each', while the help says (the help of course does)
// we must #include<algorithm> for the use of 'for_each'.
// In the case of Visual C++ Compiler (MSVC6/cl.exe), we must
// #include<algorithm> for the use of 'for_each' or we'll get
// error message during compilling.
#include <algorithm> // for_each
using namespace std;
typedef set< int, less_equal<int> > Int_set;
void printout(int& i)
{
cout << i << " ";
}
int main()
{
Int_set s; // s is sorted by "<="
s.insert(10); // insert the value 10
// print out all of 's'
cout << "First insertion: ";
for_each(s.begin(), s.end(), printout);
cout << endl;
s.insert(10); // now try inserting 10 again
cout << "Second insertion: ";
for_each(s.begin(), s.end(), printout);
cout << endl;
return 0;
}