对数组的元素进行排序

时间:2014-05-08 15:42:06

标签: c++ arrays sorting

我想对大小为a[]的数组s的成员进行排序。我首先使用函数来获取元素,然后使用另一个函数按升序对它们进行排序。问题出在sort函数中,或者在main函数中或者在两​​者中,因为程序的执行在输入数据之后就结束了。这里有人可以帮助我吗?

#include <iostream>
using namespace std;

void getdata() {
    int s;
    cin >> s;
    int a[s];

    for (int i=0; i<s; i++) {
        cin >> a[i];
    }
}

void sort(int a[], int s) {
    for (int i=0; i<s-1; i++) {
        for (int j=i+1; i<s; i++) {
            if (a[i] > a[j]) swap(a[i], a[j]);
        }
    }
}

int main () {
    int a[100],s;
    getdata();
    sort(a, s);
    return 0;
}

2 个答案:

答案 0 :(得分:1)

您在getdata()函数中有一个本地的数组定义:

void getdata() {
    int s;
    cin >> s;
    int a[s]; // <<<

它保留在那里,与你在main中声明的数组无关:

int main () {
    int a[100],s; // <<<

你必须编写你的函数,它将这些作为参数:

void getdata(int* a, int& s) {

    cin >> s;
    for (int i=0; i<s; i++) { // ...

并在主要电话中

int main () {
    int a[100],s;
    getdata(a,s);
    sort(a, s);
    return 0;
}

更新:

sort()函数的内部for循环中的条件看起来也很错误,你可能认为j没有i

for (int j=i+1; i<s; i++) {
             // ^    ^ 

答案 1 :(得分:0)

如果使用数组没有明确的优势,请始终使用std::vector(如果在编译时已知s,则在C ++ 11中使用std::array。)

#include<vector>
#include<algorithm>

std::vector<int> a;
//fill it, then
std::sort(a.begin(),a.end());
相关问题