C++ STL 演算法 — 你可能不知道的一些用法

來源:互聯網
上載者:User

distance
很多時候我們希望在一個 vector ,或者 list ,或者什麼其他東西裡面,找到一個值在哪個位置,這個時候 find 幫不上忙,而有人就轉而求助手寫迴圈了,而且是原始的手寫迴圈:

for ( int i = 0; i < vect.size(); ++i)
    if ( vect[i] == value ) break;

如果編譯器把 i 看作 for scope 的一部分,你還要把 i 的聲明拿出去。真的需要這樣嗎?看看這個:

    int dist =
        distance(col.begin(),
            find(col.begin(), col.end(), 5));

其中 col 可以是很多容器,list, vector, deque... 當然這是你確定 5 就在 col 裡面的情形,如果你不確定,那就加點判斷:

    int dist;
    list<int>::iterator pos = find(col.begin(), col.end(), 5);
    if ( pos != col.end() )
        dist = distance(col.begin(), pos);

我想這還是比手寫迴圈來的好些吧。

--------------------------------------------------------------------------
max, min
這是有直接的演算法支援的,當然複雜度是 O(n),用於未排序容器,如果是排序容器...老兄,那還需要什麼演算法嗎?

max_element(col.begin(), col.end());
min_element(col.begin(), col.end());

注意返回的是 iterator ,如果你關心的只是值,那麼好:

*max_element(col.begin(), col.end());
*min_element(col.begin(), col.end());

max_element 和 min_element 都預設用 less 來排序,它們也都接受一個 binary predicate ,如果你足夠無聊,甚至可以把 max_element 當成 min_element 來用,或者反之:

*max_element(col.begin(), col.end(), greater<int>()); // 返回最小值!
*min_element(col.begin(), col.end(), greater<int>()); // 返回最大值

當然它們的本意不是這個,而是讓你能在比較特殊的情況下使用它們,例如,你要比較的是每個元素的某個成員,或者成員函數的傳回值。例如:

#include <iostream>
#include <list>
#include <algorithm>
#include <string>
#include <boost/bind.hpp>

using namespace boost;
using namespace std;

struct Person
{
    Person(const string& _name, int _age)
        : name(_name), age(_age)
    {}
    int age;
    string name;
};

int main()
{
    list<Person> col;
    list<Person>::iterator pos;

    col.push_back(Person("Tom", 10));
    col.push_back(Person("Jerry", 12));
    col.push_back(Person("Mickey", 9));

    Person eldest =
        *max_element(col.begin(), col.end(),
            bind(&Person::age, _1) < bind(&Person::age, _2));
   
    cout << eldest.name;
}

輸出是 Jerry ,這裡用了 boost.bind ,原諒我不知道用 bind2nd, mem_fun 怎麼寫,我也不想知道...

-------------------------------------------------------------------------
copy_if
沒錯,STL 裡面壓根沒有 copy_if ,這就是為什麼我們需要這個:

template<typename InputIterator, typename OutputIterator, typename Predicate>
OutputIterator copy_if(
    InputIterator begin, InputIterator end, OutputIterator destBegin, Predicate p)
{
    while (begin != end)
    {
        if (p(*begin))*destBegin++ = *begin;
        ++begin;
    }
    return destBegin;
}

把它放在自己的工具箱裡,是一個明智的選擇。

------------------------------------------------------------------------
慣用手法:erase(iter++)
如果你要去除一個 list 中的某些元素,那可千萬小心:(下面的代碼是錯的!!!)

#include <iostream>
#include <algorithm>
#include <iterator>
#include <list>

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::list<int> lst(arr, arr + 10);

    for ( std::list<int>::iterator iter = lst.begin();
          iter != lst.end(); ++iter)
        if ( *iter % 2 == 0 )
            lst.erase(iter);
           
    std::copy(lst.begin(), lst.end(),
        std::ostream_iterator<int>(std::cout, " "));
}

當 iter 被 erase 掉的時候,它已經失效,而後面卻還會做 ++iter ,其行為無可預期!如果你不想動用 remove_if ,那麼唯一的選擇就是:

#include <iostream>
#include <algorithm>
#include <iterator>
#include <list>

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::list<int> lst(arr, arr + 10);

    for ( std::list<int>::iterator iter = lst.begin();
          iter != lst.end(); )
        if ( *iter % 2 == 0 )
            lst.erase(iter++);
        else
            ++iter;
          
    std::copy(lst.begin(), lst.end(),
        std::ostream_iterator<int>(std::cout, " "));
}

但是上面的代碼不能用於 vector, string 和 deque ,因為對於這些容器, erase 不光令 iter 失效,還令 iter 之後的所有 iterator 失效!

-------------------------------------------------------------------------
erase(remove...) 慣用手法
上面的迴圈如此難寫,如此不通用,如此不容易理解,還是用 STL 演算法來的好,但是注意,光 remove_if 是沒用的,必須使用 erase(remove...) 慣用手法:

#include <iostream>
#include <algorithm>
#include <iterator>
#include <list>
#include <functional>
#include <boost/bind.hpp>

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::list<int> lst(arr, arr + 10);

    lst.erase(remove_if(lst.begin(), lst.end(),
        boost::bind(std::modulus<int>(), _1, 2) == 0),
        lst.end()
    );
          
    std::copy(lst.begin(), lst.end(),
        std::ostream_iterator<int>(std::cout, " "));
}

當然,這裡藉助了 boost.bind ,讓我們不用多寫一個沒用的 functor 。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.