星期二, 8月 10, 2010

嘗試在VS2010中使用C++0x的shared_ptr以及lambda expression搭配STL container

#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>

using namespace std;

class Base{
public:
    int m_i;
    Base(int i):m_i(i) {}
    ~Base(){ cout << m_i << "~Base()" << endl; }
};

class Derived: public Base{
public:
    Derived(int i):Base(i) { }
    ~Derived(){
        cout << "~Derived()" << endl;
    }
};

int main()
{
    vector< shared_ptr<Base> > v;
    v.push_back(shared_ptr<Base>(new Derived(1)));
    v.push_back(shared_ptr<Base>(new Derived(2)));
    sort(v.begin(), v.end(), [](shared_ptr<Base> a, shared_ptr<Base> b){
        return a->m_i > b->m_i;
    });

    for_each(v.begin(), v.end(), [](shared_ptr<Base> a){
        cout << a->m_i << "\t";
    });
    cout << endl;
    return 0;
}