zoukankan      html  css  js  c++  java
  • 一些STL,string的算法

    toupper, tolower
    地球人都知道 C++ 的 string 没有 toupper ,好在这不是个大问题,因为我们有 STL 算法:

    string s("heLLo");
    transform(s.begin(), s.end(), s.begin(), toupper);
    cout << s << endl;
    transform(s.begin(), s.end(), s.begin(), tolower);
    cout << s << endl;

    当然,我知道很多人希望的是 s.to_upper() ,但是对于一个这么通用的 basic_string 来说,的确没办法把这些专有的方法放进来。如果你用 boost stringalgo ,那当然不在话下,你也就不需要读这篇文章了。

    ------------------------------------------------------------------------
    trim
    我们还知道 string 没有 trim ,不过自力更生也不困难,比 toupper 来的还要简单:

        string s("   hello   ");
        s.erase(0, s.find_first_not_of(" /n"));
        cout << s << endl;
        s.erase(s.find_last_not_of(' ') + 1);
        cout << s << endl;

    注意由于 find_first_not_of 和 find_last_not_of 都可以接受字符串,这个时候它们寻找该字符串中所有字符的 absence ,所以你可以一次 trim 掉多种字符。

    -----------------------------------------------------------------------
    erase
    string 本身的 erase 还是不错的,但是只能 erase 连续字符,如果要拿掉一个字符串里面所有的某个字符呢?用 STL 的 erase + remove_if 就可以了,注意光 remove_if 是不行的。

        string s("   hello, world. say bye   ");
        s.erase(remove_if(s.begin(),s.end(),
            bind2nd(equal_to<char>(), ' ')),
        s.end());

    上面的这段会拿掉所有的空格,于是得到 hello,world.saybye。

    -----------------------------------------------------------------------
    replace
    string 本身提供了 replace ,不过并不是面向字符串的,譬如我们最常用的把一个 substr 换成另一个 substr 的操作,就要做一点小组合:

        string s("hello, world");
        string sub("ello, ");
        s.replace(s.find(sub), sub.size(), "appy ");
        cout << s << endl;

    输出为 happy world。注意原来的那个 substr 和替换的 substr 并不一定要一样长。

    -----------------------------------------------------------------------
    startwith, endwith
    这两个可真常用,不过如果你仔细看看 string 的接口,就会发现其实没必要专门提供这两个方法,已经有的接口可以干得很好:

        string s("hello, world");
        string head("hello");
        string tail("ld");
        bool startwith = s.compare(0, head.size(), head) == 0;
        cout << boolalpha << startwith << endl;
        bool endwith = s.compare(s.size() - tail.size(), tail.size(), tail) == 0;
        cout << boolalpha << endwith << endl;

    当然了,没有 s.startwith("hello") 这样方便。

    ------------------------------------------------------------------------
    toint, todouble, tobool...
    这也是老生常谈了,无论是 C 的方法还是 C++ 的方法都可以,各有特色:

        string s("123");
        int i = atoi(s.c_str());
        cout << i << endl;
       
        int ii;
        stringstream(s) >> ii;
        cout << ii << endl;
       
        string sd("12.3");
        double d = atof(sd.c_str());
        cout << d << endl;
       
        double dd;
        stringstream(sd) >> dd;
        cout << dd << endl;
       
        string sb("true");
        bool b;
        stringstream(sb) >> boolalpha >> b;
        cout << boolalpha << b << endl;

    C 的方法很简洁,而且赋值与转换在一句里面完成,而 C++ 的方法很通用。

    ------------------------------------------------------------------------
    split
    这可是件麻烦事,我们最希望的是这样一个接口: s.split(vect, ',') 。用 STL 算法来做有一定难度,我们可以从简单的开始,如果分隔符是空格、tab 和回车之类,那么这样就够了:

        string s("hello world, bye.");
        vector<string> vect;
        vect.assign(

            istream_iterator<string>(stringstream(s)),

            istream_iterator<string>()

        );


    不过要注意,如果 s 很大,那么会有效率上的隐忧,因为 stringstream 会 copy 一份 string 给自己用。

    ------------------------------------------------------------------------
    concat
    把一个装有 string 的容器里面所有的 string 连接起来,怎么做?希望你不要说是 hand code 循环,这样做不是更好?

        vector<string> vect;
        vect.push_back("hello");
        vect.push_back(", ");
        vect.push_back("world");
       
        cout << accumulate(vect.begin(), vect.end(), string(""));

    不过在效率上比较有优化余地。

    -------------------------------------------------------------------------

    reverse
    其实我比较怀疑有什么人需要真的去 reverse 一个 string ,不过做这件事情的确是很容易:

      std::reverse(s.begin(), s.end());

    上面是原地反转的方法,如果需要反转到别的 string 里面,一样简单:

      s1.assign(s.rbegin(), s.rend());

    效率也相当理想。

    -------------------------------------------------------------------------

    解析文件扩展名
    字数多点的写法:

        std::string filename("hello.exe");

        std::string::size_type pos = filename.rfind('.');
        std::string ext = filename.substr(pos == std::string::npos ? filename.length() : pos + 1);

    不过两行,合并成一行呢?也不是不可以:

        std::string ext = filename.substr(filename.rfind('.') == std::string::npos ? filename.length() : filename.rfind('.') + 1);

    我知道,rfind 执行了两次。不过第一,你可以希望编译器把它优化掉,其次,扩展名一般都很短,即便多执行一次,区别应该是相当微小。

    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 。
       

  • 相关阅读:
    scanf的参数类型自动转换
    Gedit中文乱码
    在VirtualBox的Ubuntu虚拟机中与母体Windows共享文件夹
    Win7安vc2008编译报LINK : fatal error LNK1000: Internal error during IncrBuildImage
    贝叶斯后验概率小记
    美国计算机专业最好的前20名学校
    Linux磁盘空间不够怎么办?
    Debian6.0装机过程
    把用户加到sudoers组中的方法
    vi命令手册
  • 原文地址:https://www.cnblogs.com/kex1n/p/2286420.html
Copyright © 2011-2022 走看看