using sort() in STL to sort an array

后端 未结 6 2150
无人共我
无人共我 2020-12-10 19:31

I am writing code for a question which is: Write a method to sort an array of strings so that all the anagrams are next to each other. If my container is vector, it will be

6条回答
  •  天涯浪人
    2020-12-10 19:48

    The free functions std::begin() and std::end() (since C++11) are specialized for array types, but the size must be known to the compiler:

    template 
    int sortStrarr(T array[N])
    {
        // 'using' allows ADL to select best overload
        using std::begin;
        using std::end;
        std::sort(begin(array), end(array));
    }
    

    If you have only the start and (run-time) size, then you can use pointers as the iterators:

    template 
    int sortStrarr(T array[], size_t len)
    {
        std::sort(array, array+len);
    }
    

提交回复
热议问题