STL演算法find_if和find

來源:互聯網
上載者:User

根據effective STL的rule,從效率和正確性角度考慮,使用STL的演算法要比自己寫迴圈遍曆要effective。之前一直沒講究過這個。從現在起,要注意起來了。先學起來下面三個

1. find

2. find_if

3. for_each

它們都會用到mem_fun, mem_fun1(可以接受一個參數),bind2nd(ptr_fun(funcName), argument)。詳見下面的例子(來自:http://www.builder.com.cn/2008/0129/723326.shtml)

比如我們有下面的類:class ClxECS
{
public:
    int DoSomething() 
    { 
        // 這裡以輸出一句話來代替具體的操作
        cout << "Output from method DoSomething!" << endl; 
        return 0; 
    };
};

    和下面的一個vector:

vector<ClxECS*> vECS;

for (int i = 0; i < 13; i++)
{
    ClxECS *pECS = new ClxECS;
    vECS.push_back(pECS);
}

    如果要對容器vECS中的所有對象都進行DoSomething()的操作,可以用下面的方法:

for_each(vECS.begin(), vECS.end(), mem_fun(&ClxECS::DoSomething)); // 對每個element調用其成員函數DoSomething()

    (關於mem_fun的用法可以參考我的那篇《STL中mem_fun和mem_fun_ref的用法》)
    當然,我們也可以用下面的方法:

int DoSomething(ClxECS *pECS)  
{
return pECS->DoSomething();
}

for_each(vECS.begin(), vECS.end(), &DoSomething); // 對每個element調用DoSomething函數,把它自己當參數傳入。

    從上面的代碼可以看到,兩種方法其實都是調用類ClxECS的DoSomething()方法。在這裡,方法DoSomething()是沒有參數的,如果這個方法像下面那樣是有參數的,該用什麼方法傳遞參數呢?

class ClxECS
{
public:
    int DoSomething(int iValue)
    {
        cout << "Do something in class ClxECS!" << endl;
        cout << "The input value is: " << iValue << endl;
        return 0;
    }
};

    這個時候就該我們的bind2nd登場了!下面是具體的代碼:

// mem_fun1是mem_fun支援一個參數的版本
for_each(vECS.begin(), vECS.end(), bind2nd(mem_fun1(&ClxECS::DoSomething), 13));

    或者:

int DoSomething(ClxECS *pECS, int iValue)
{
    return pECS->DoSomething(iValue);
}

for_each(vECS.begin(), vECS.end(), bind2nd(ptr_fun(DoSomething), 13));

    從上面的代碼可以看出,bind2nd的作用就是綁定函數子的參數的。可是STL只提供了對一個參數的支援。如果函數的參數多於1個,那就無能為力了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.