#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
template <class T>
void PRINT_ELEMENTS (const T& coll, const char* optcstr ="")
{
typename T::const_iterator pos;
std::cout << optcstr;
for (pos=coll.begin(); pos!=coll.end(); ++pos) {
std::cout << *pos << ' ';
}
std::cout << std::endl;
}
class IntSequence{
private:
int _value;
public:
IntSequence( int initialValue )
: _value( initialValue ){}
int operator()( ){ return _value++; }
int value(){ return _value; }
};
int main(){
list< int > coll;
IntSequence seq( 1 );
generate_n< back_insert_iterator< list<int> >, int,IntSequence& >( back_inserter(coll), 4, seq ); // seq欲传引用,改变seq._value的值
PRINT_ELEMENTS( coll );
generate_n( back_inserter(coll), 4, IntSequence(42) );
PRINT_ELEMENTS( coll );
generate_n( back_inserter(coll), 4, const_cast<IntSequence &>(seq) );
PRINT_ELEMENTS( coll );
generate_n( back_inserter(coll), 4, const_cast<IntSequence &>(seq) );
PRINT_ELEMENTS( coll );
}
//在dev-cpp下输出如下:
1 2 3 4
1 2 3 4 42 43 44 45
1 2 3 4 42 43 44 45 5 6 7 8
1 2 3 4 42 43 44 45 5 6 7 8 5 6 7 8
请按任意键继续. . .
//而在VS2010下输出如下:
1 2 3 4
1 2 3 4 42 43 44 45
1 2 3 4 42 43 44 45 1 2 3 4
1 2 3 4 42 43 44 45 1 2 3 4 1 2 3 4
请按任意键继续. . .
森栏