using sort() in STL to sort an array

后端 未结 6 2132
无人共我
无人共我 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:33

    Pointers can act as iterators, so you just need pointers to the beginning and just past the end of the array.

    0 讨论(0)
  • 2020-12-10 19:36
    int sortStrarr(string strarr[], int len){
         sort(&strarr[0],&strarr[len],compare) ;
        //sort(strarr's iterator.begin, strarr's iterator.end, compare); ???
    }
    
    0 讨论(0)
  • 2020-12-10 19:40

    We have to use sort function to sort the string array.

    int main()
    {
       string arr[5] = {"e", "b", "c", "d", "a'};
       sort(arr, arr+5);
       for(int i=0; i<5; i++)
       {
         cout<<arr.at(i)<<" ";
       }
       return 0;
    }
    
    0 讨论(0)
  • 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 <typename T, std::size_t N>
    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 <typename T>
    int sortStrarr(T array[], size_t len)
    {
        std::sort(array, array+len);
    }
    
    0 讨论(0)
  • 2020-12-10 19:49

    You can use sort() for an array. Pointers act as iterators.

    Example:

    #include <iostream>
    #include <string>
    #include <algorithm>
    using namespace std;
    
    int main()
    {
        string arr[5]={"BBB","AAA","CCC","FFF", "EEE"};
        sort(arr,arr+5);
        for(string i: arr)
        {
            cout << i << endl;
        }
    }
    

    and the output is:

    AAA
    BBB
    CCC
    EEE
    FFF
    
    0 讨论(0)
  • 2020-12-10 19:54

    As (like in C) array can be casted to pointer to the first element (but please, do not confuse array with pointer) you can use pointers to determine begin and end, so you write:

    sort(strarr, strarr + len, compare);
    

    or if you use C++11 (or Boost) you can use array class:

    template<std::size_t N>
    int sortStrarr(std:array<string, N>& strarr, int len){
        sort(strarr.begin(), strarr.end(), compare);
    }
    
    0 讨论(0)
提交回复
热议问题