C++ STL函数对象
cfunctionobject2020101101.cpp
//cfunctionobject2020101101.cpp #include <iostream> #include <list> #include <algorithm> #include <iterator> #include "print.hpp" using namespace std; class IntSequence { private: int value; public: IntSequence(int initialValue):value(initialValue) {} // int operator() () { return ++value; } }; int main() { list<int> coll; //insert values from 1 to 9 generate_n(back_inserter(coll), 9, IntSequence(1)); PRINT_ELEMENTS(coll); //replace seconds to last element but one with values starting at 42 generate(next(coll.begin()), prev(coll.end()), IntSequence(42)); PRINT_ELEMENTS(coll); }
print.hpp
//print.hpp #include <iostream> #include <string> template <typename T> inline void PRINT_ELEMENTS(const T& coll, const std::string& optstr = "") { std::cout << optstr; for (const auto& elem : coll) { std::cout << elem << " "; } std::cout << std::endl; }
运行结果
2 3 4 5 6 7 8 9 10
2 43 44 45 46 47 48 49 10