C ++排序动态字符串数组 - 排序不起作用

时间:2016-12-26 19:33:19

标签: c++

我是C ++的新手,我希望对std :: cin提供的动态字符串数组进行排序。

我不知道我的代码有什么问题,但数组没有排序。

#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

void sort_array(string *array);

int main() {
    cout << "Number of names to enter: " << endl;
    int nr_names;
    cin >> nr_names;
    string *names = new (nothrow) string[nr_names];

    if (names == nullptr) {
        cout << "Memory alocation failed" << endl;
    } else {
        for (int i = 0; i < nr_names; i++) {
            cout << "Enter a name: " << endl;
            cin >> names[i];
        }
        cout << "Entered names are: " << endl;
        for (int i = 0; i < nr_names; i++) {
            cout << names[i] << endl;
        }

        sort_array(names);

        cout << "Sorted names: " << endl;
        for (int i = 0; i < nr_names; i++) {
            cout << names[i] << endl;
        }
        delete[] names;
    }
    return 0;
}

void sort_array(string *array) {
    const int arSize = (sizeof(*array) / sizeof(array[0]) - 1);
    for (int startIndex = 0; startIndex < arSize; startIndex++) {
        int smallestIndex = startIndex;

        for (int currentIndex = startIndex+1; currentIndex < arSize; currentIndex++) {
            if (array[currentIndex] < array[smallestIndex]) {
                smallestIndex = currentIndex;
            }
        }
    swap(array[startIndex], array[smallestIndex]);
    }
}

排序方法适用于固定数组。所以我认为动态内存分配可能存在一些问题(我刚开始研究)

#include <algorithm>
#include <iostream>
#include <string>
using namespace std;


int main() {
    string array[5] ={"Mike", "Andrew", "Bob", "Nick", "Matthew"};
    const int arSize = 5;
    for (int startIndex = 0; startIndex < arSize; startIndex++) {
        int smallestIndex = startIndex;

        for (int currentIndex = startIndex+1; currentIndex < arSize; currentIndex++) {
            if (array[currentIndex] < array[smallestIndex]) {
                smallestIndex = currentIndex;
            }
        }
        swap(array[startIndex], array[smallestIndex]);
    }
    //print the sorted array - works
    for(int i = 0; i< arSize; i++){
        cout<<array[i]<<endl;
    }
}

1 个答案:

答案 0 :(得分:0)

void sort_array(string *array)中,数组未被排序,因为const int arSize = (sizeof(*array) / sizeof(array[0]) - 1);不是数组大小。这是...... 0。

它应该是const int arSize = sizeof(array) / sizeof(array[0])但仅在array是数组时才有效,而不是元素上的指针。

所以你的循环永远不会执行(所以你必须传递大小)

正如Justin评论的那样,由于您使用的是C ++和高级swap内容,std::vector是传递大小数组的方法。