【问题标题】:How to use std::sort to sort an array in C++如何使用 std::sort 在 C++ 中对数组进行排序
【发布时间】:2011-08-19 07:58:55
【问题描述】:

如何使用标准模板库std::sort() 对声明为的数组进行排序 int v[2000];

C++ 是否提供了一些函数可以获取数组的开始和结束索引?

【问题讨论】:

    标签: c++ sorting


    【解决方案1】:

    在 C++0x/11 中,我们得到 std::beginstd::end,它们为数组重载:

    #include <algorithm>
    
    int main(){
      int v[2000];
      std::sort(std::begin(v), std::end(v));
    }
    

    如果你没有 C++0x 的访问权限,自己编写它们并不难:

    // for container with nested typedefs, non-const version
    template<class Cont>
    typename Cont::iterator begin(Cont& c){
      return c.begin();
    }
    
    template<class Cont>
    typename Cont::iterator end(Cont& c){
      return c.end();
    }
    
    // const version
    template<class Cont>
    typename Cont::const_iterator begin(Cont const& c){
      return c.begin();
    }
    
    template<class Cont>
    typename Cont::const_iterator end(Cont const& c){
      return c.end();
    }
    
    // overloads for C style arrays
    template<class T, std::size_t N>
    T* begin(T (&arr)[N]){
      return &arr[0];
    }
    
    template<class T, std::size_t N>
    T* end(T (&arr)[N]){
      return arr + N;
    }
    

    【讨论】:

    • std::begin()std::end() C++1x 的补充吗?它们非常好——从一开始就应该是这样,它会让很多算法更通用!
    • std::begin()std::end() 不是当前 C++ 标准的一部分,但您可以使用 boost::begin()boost::end()
    • 根据 cmets 编辑。
    • 提醒一下:早在他们为 C++11 提出建议之前,我们大多数人的个人工具包中就有 beginend 函数。然而,在 C++11 之前,它们有一个严重的缺点:它们不会产生整数常量表达式。所以根据具体需要,我们会使用它们,或者使用一个宏来划分两个sizeof
    • @Xeo 我不确定我明白你在说什么。 decltype 当然简化了某些用途,但我看不出它与免费的 beginend 函数有什么关系。 (你真的应该有两个,一个用于 C 样式数组,另一个用于容器,具有自动识别功能,因此您可以在模板中使用它们,而无需知道类型是容器还是 C 样式数组。)
    【解决方案2】:
    #include <algorithm>
    static const size_t v_size = 2000;
    int v[v_size];
    // Fill the array by values
    std::sort(v,v+v_size); 
    

    C++11:

    #include <algorithm>
    #include <array>
    std::array<int, 2000> v;
    // Fill the array by values
    std::sort(v.begin(),v.end()); 
    

    【讨论】:

    • +1:正确但非常脆弱。如果排序不在声明附近,这很容易在维护期间被破坏。
    • @Martin:是的。这就是为什么我更喜欢使用std::vector。我的代码是:std::vector&lt;int&gt; v(2000); std::sort( v.begin(), v.end() );
    • 当然,使用字面量数组大小总是很危险的,如示例中所示。但是将数组大小放入'const int'并没有错。
    【解决方案3】:

    如果不知道大小,可以使用:

    std::sort(v, v + sizeof v / sizeof v[0]);
    

    即使您确实知道大小,也最好以这种方式编码,因为如果以后更改数组大小,它将减少出现错误的可能性。

    【讨论】:

    • 如果是静态分配的,他应该知道大小,因为编译器知道。但这是更好的编码实践。
    • 由于您正在编写未来证明代码,而不是使用sizeof x/sizeof *x 技巧,您应该使用更安全的模板:template &lt;typename T, int N&gt; int array_size( T (&amp;)[N] ) { return N; },因为如果您传递的是指针而不是数组,那将会失败。如果需要,可以将其转换为编译时间常数,但在注释中阅读起来有点困难。
    • @David:好主意,但更好的(我敢说是正确的)方法是定义专门用于所有常见容器类型(包括数组)的 begin()end() 函数模板,并改用它们。 Xeo 的回答让我觉得这些已经被添加到 C++ 中,现在看来他们还没有……我会看看人们还有什么要说的,然后更新。
    • :) 我有一个小的实用程序标头,其中包含一些这样的位,包括beginendsizeSTATIC_SIZE(返回编译时间常数的宏size),但老实说,除了小代码示例之外,我几乎从不使用它。
    • C++11中std::extent&lt;decltype(v)&gt;::value可以接收数组的大小
    【解决方案4】:

    你可以排序std::sort(v, v + 2000)

    【讨论】:

    • +1:正确但非常脆弱。如果排序不在声明附近,这很容易在维护期间被破坏。
    【解决方案5】:
    //It is working
    #include<iostream>
    using namespace std;
    void main()
    {
        int a[5];
        int temp=0;
        cout<<"Enter Values"<<endl;
        for(int i=0;i<5;i++)
        {
            cin>>a[i];
        }
        for(int i=0;i<5;i++)
        {
            for(int j=0;j<5;j++)
            {
                if(a[i]>a[j])
                {
                    temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
            }
        }
        cout<<"Asending Series"<<endl;
        for(int i=0;i<5;i++)
        {
            cout<<endl;
            cout<<a[i]<<endl;
        }
    
    
        for(int i=0;i<5;i++)
        {
            for(int j=0;j<5;j++)
            {
                if(a[i]<a[j])
                {
                    temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
            }
        }
        cout<<"Desnding Series"<<endl;
        for(int i=0;i<5;i++)
        {
            cout<<endl;
            cout<<a[i]<<endl;
        }
    
    
    }
    

    【讨论】:

      【解决方案6】:

      您可以在 C++ STL 中使用 sort()。 sort() 函数语法:

       sort(array_name, array_name+size)      
      
       So you use  sort(v, v+2000);
      

      【讨论】:

        【解决方案7】:

        就这么简单...C++ 在 STL(标准模板库)中为您提供了一个名为 sort 的函数,它的运行速度比手动编码的快速排序快 20% 到 50%。

        这是它的使用示例代码:

        std::sort(arr, arr + size);
        

        【讨论】:

          【解决方案8】:
          //sort by number
          bool sortByStartNumber(Player &p1, Player &p2) {
              return p1.getStartNumber() < p2.getStartNumber();
          }
          //sort by string
          bool sortByName(Player &p1, Player &p2) {
              string s1 = p1.getFullName();
              string s2 = p2.getFullName();
              return s1.compare(s2) == -1;
          }
          

          【讨论】:

          • 欢迎来到 Stack Overflow。只提供代码而没有任何解释的答案通常是不受欢迎的,尤其是当 a) 已经提供了许多答案,并且 b) 一个答案已经被接受时。请详细说明为什么您的解决方案与已经发布的 12 个不同和/或更好。
          【解决方案9】:

          借助 C++20 中的 Ranges 库,您可以使用

          ranges::sort(arr);
          

          直接,其中arr 是一个内置数组。

          【讨论】:

            【解决方案10】:

            不带std::sort的排序方法:

            // sorting myArray ascending
            int iTemp = 0;
            for (int i = 0; i < ARRAYSIZE; i++)
            {
                for (int j = i + 1; j <= ARRAYSIZE; j++)
                {
                    // for descending sort change '<' with '>'
                    if (myArray[j] < myArray[i])
                    {
                        iTemp = myArray[i];
                        myArray[i] = myArray[j];
                        myArray[j] = iTemp;
                    }
                }
            }
            

            Run 完整示例:

            #include <iostream> // std::cout, std::endl /* http://en.cppreference.com/w/cpp/header/iostream */
            #include <cstdlib>  // srand(), rand()      /* http://en.cppreference.com/w/cpp/header/cstdlib */
            #include <ctime>    // time()               /* http://en.cppreference.com/w/cpp/header/ctime */
            
            
            int main()
            {
                const int ARRAYSIZE = 10;
                int myArray[ARRAYSIZE];
            
                // populate myArray with random numbers from 1 to 1000
                srand(time(0));
                for (int i = 0; i < ARRAYSIZE; i++)
                {
                    myArray[i] = rand()% 1000 + 1;
                }
            
                // print unsorted myArray
                std::cout << "unsorted myArray: " << std::endl;
                for (int i = 0; i < ARRAYSIZE; i++)
                {
                    std::cout << "[" << i << "] -> " << myArray[i] << std::endl;
                }
                std::cout << std::endl;
            
                // sorting myArray ascending
                int iTemp = 0;
                for (int i = 0; i < ARRAYSIZE; i++)
                {
                    for (int j = i + 1; j <= ARRAYSIZE; j++)
                    {
                        // for descending sort change '<' with '>'
                        if (myArray[j] < myArray[i])
                        {
                            iTemp = myArray[i];
                            myArray[i] = myArray[j];
                            myArray[j] = iTemp;
                        }
                    }
                }
            
                // print sorted myArray
                std::cout << "sorted myArray: " << std::endl;
                for (int i = 0; i < ARRAYSIZE; i++)
                {
                    std::cout << "[" << i << "] -> " << myArray[i] << std::endl;
                }
                std::cout << std::endl;
            
                return 0;
            }
            

            【讨论】:

            • 真的吗?您想使用慢速冒泡排序而不是标准库吗?不仅如此,您还有一个导致 UB 的错误。
            【解决方案11】:

            使用排序函数的C++排序

            #include <bits/stdc++.h>
             using namespace std;
            
            vector <int> v[100];
            
            int main()
            {
              sort(v.begin(), v.end());
            }
            

            【讨论】:

            • 这个适用于旧版本。我试过这个:std::sort(arr, arr + arr_size)
            • 这根本不起作用。不是说它不是 C++。
            【解决方案12】:

            使用 C++ std::sort 函数:

            #include <algorithm>
            using namespace std;
            
            int main()
            {
              vector<int> v(2000);
              sort(v.begin(), v.end());
            }
            

            【讨论】:

              【解决方案13】:

              你可以使用,

               std::sort(v.begin(),v.end());
              

              【讨论】:

              • 嗨,这个问题似乎已经有了一个被广泛接受的答案。你能解释一下这有什么不同吗?
              • 数组没有 beginend 方法。你一定在想vector
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2018-11-20
              • 1970-01-01
              • 1970-01-01
              • 2016-11-20
              • 1970-01-01
              • 2021-05-28
              • 2016-09-11
              相关资源
              最近更新 更多