C++从小到大排序数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5101997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:24:10  来源:igfitidea点击:

C++ sorting numbers from smallest to biggest

c++sortingnumbers

提问by Oliver

If I have the user enter 10 random numbers and I want to order them from smallest to biggest what is the best method to do this using the most basic C++ language.

如果我让用户输入 10 个随机数,并且我想将它们从小到大排序,那么使用最基本的 C++ 语言执行此操作的最佳方法是什么。

回答by Jerry Coffin

std::vector<int> numbers;

// get the numbers from the user here.    

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

回答by pyfex

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int main() {

    vector<int> vec;

    vec.push_back(1);
    vec.push_back(4);
    vec.push_back(3);
    vec.push_back(2);

    sort( vec.begin(), vec.end() );

    for (vector<int>::const_iterator it=vec.begin(); it!=vec.end(); ++it) {
      cout << *it << " ";
    }
    cout << endl;
    return 0;
}

回答by Matthieu M.

Use a structure that maintains ordering: std::multiset

使用保持排序的结构:std::multiset

#include <iostream>
#include <set>

#include <boost/lexical_cast.hpp>

int main(int argc, char* argv[])
{
  std::multiset<int> set;

  for (int i = 1; i != argc; ++i) {
    set.insert(boost::lexical_cast<int>(argv[i]));
  }

  for (int i: set) { std::cout << i << " "; }
  std::cout << "\n";
}

Invocation:

调用:

$ yourprogram 1 5 4 6 7 82 6 7 8

(Note: the number of arguments is not constrained)

(注意:参数数量不受限制)

回答by Leo Ivas

    //this is sorting min--->max without pointers
    #include<iostream>
    using namespace std;
    int main()
    {int n;
    cout<<"How much numbers you wanna sort? "<<endl;
    cin>>n;
    int broj[n];
    cout<<"Enter numbers: "<<endl;
    for(int k=0;k<n;k++)
    {
    cin>>broj[k];
    }
    int min=0;
    for(int z=0;z<n;z++)
    {
    loop:
    min=broj[z];

    for(int i=z;i<n;i++)
   {
        if(min<=broj[i])
        {
        }
        else
        {
             min=broj[i];
             broj[i]=broj[z];
             broj[z]=min;
             goto loop;         
         }
   }
   }
   cout<<endl<<"--------------"<<endl;
   for(int j=0;j<n;j++)
   {
   cout<<broj[j]<<endl;
   }
   return 0;
   }

回答by MM.

It depends on your requirements. If you just want to sort them, and speed is only of moderate concern, an insertion sort would be fine for such a small n-value (10). Quick to implement (from scratch), and suitable for small set sizes.

这取决于您的要求。如果您只是想对它们进行排序,并且速度只是中等问题,那么对于如此小的 n 值 (10),插入排序就可以了。快速实施(从头开始),适用于小尺寸。

回答by Oleg

You can write something yourself, but really should use qsort function.

你可以自己写一些东西,但真的应该使用 qsort 函数。