- 论坛徽章:
- 0
|
求教: for_each跟STL问题
- #include <iostream>;
- #include <cstdlib>;
- #include <algorithm>;
- #include <map>;
- #include <functional>;
- #include <string>;
- using namespace std;
- //for_each要求print functor是一个从unary_function继承而来的。
- //unary_function在这里使用TYPE作为模板参数,返回void类型,
- //返回值的类型也是unary_function要求的。
- template <class TYPE>;
- struct print : public unary_function<TYPE, void>;
- {
- void operator()(TYPE& x)
- {
- cout << x.first << "\t"<< *(x.second) << endl;
- }
- };
- //逐项清除动态分配的对象,防止内存泄漏
- template <class TYPE>;
- struct deleteFrom : public unary_function<TYPE, void>;
- {
- void operator()(TYPE& x)
- {
- delete x.second;
- }
- } ;
- class Test
- {
- //前两个友元函数无用,只是考虑Test作为键时Test必须实现的
- friend bool operator<(const Test& test1, const Test& test2);
- friend bool operator==(const Test& test1, const Test& test2);
- //输出流运算符重载
- friend ostream& operator<<(ostream& os, const Test& test);
- public:
- Test(int val = 0)
- {
- value_ = val;
- }
-
- private:
- int value_;
- };
- bool operator<(const Test& test1, const Test& test2)
- {
- return (test1.value_ < test2.value_);
- }
- bool operator==(const Test& test1, const Test& test2)
- {
- return (test1.value_ == test2.value_);
- }
- ostream& operator<<(ostream& os, const Test& test)
- {
- os << test.value_ << " ";
- return os;
- }
- int main(int argc, char *argv[])
- {
-
- map<string, Test*>; mymap;
- string str = "first";
- mymap[str] = new Test(1);
- str = "second";
- mymap[str] = new Test(2);
- str = "third";
- mymap[str] = new Test(3);
- /**
- * 假如你使用
- * mymap["first"] = new Test(1);
- * mymap["second"] = new Test(2);
- * mymap["third"] = new Test(3)
- * 这时
- * 要注意const属性
- * for_each应当写成
- * for_each(mymap.begin(), mymap.end(), print< map< const string, Test*>;::value_type >; () );
- **/
- //map的每一项是一个<键,值>;对
- for_each(mymap.begin(), mymap.end(), print< map< string, Test* >;::value_type >;());
- for_each(mymap.begin(), mymap.end(), deleteFrom< map< string, Test *>;::value_type>;());
- mymap.clear(); //这句可以不调用,mymap析构函数应当自动调用。
- cout << "Now mymap has " << mymap.size() << " items"<< endl;
- system("PAUSE");
- return 0;
- }
复制代码 |
|