对字符数组中的单词进行排序

时间:2013-09-24 21:10:17

标签: c++ arrays pointers character

对于给定的数组,我需要编写一个函数来按字母顺序对单词进行排序:

char strings [][10] = {
    "hello",
    "world",
    "computers",
    "are",
    "awesome"
};

我尝试使用插入排序编写函数sortWords,但我认为我的交换函数不起作用:

void swap(char *e1, char *e2) {
    int tmp = *e1;
    *e1 = *e2;
    *e2 = tmp;
}

void sortWords( char (* words2Darray)[10], unsigned short length ) {
    unsigned int i, curPos;
    char curChars[10];

    for(i = 1; i < length; i++) {
        // Copy the current word into curChars
        strncpy_s(curChars, words2Darray[i], 10);
        curPos = i;

        // Compare and move the word to the correct position
        while(curPos > 0 && strcmp(curChars, words2Darray[i-1]) > 0) {
            swap(words2Darray[curPos], words2Darray[curPos-1]);
            curPos--;
        }
    }
}

我尝试使用Local Windows Debugger调试我的代码,发现正在正确复制curChars

有人可以向我解释我的错误以及如何解决这个问题?我不允许在这个问题中使用std::string请不要提供完整的解决方案!

2 个答案:

答案 0 :(得分:2)

您可以使用std::sort

std::sort(std::begin(strings), std::end(strings), cmp);

这需要一个比较器。我根据strcmp鞭打了一个。

查看 Live on IdeOne

#include <algorithm>
#include <iostream>
#include <cstring>

int main()
{
    char const* strings[] = {
        "hello",
        "world",
        "computers",
        "are",
        "awesome"
    };

    struct { 
        bool operator()(char const* a, char const* b) const {
            return (a && b)? 0 > strcmp(a,b) : a < b;
        }
    } cmp;

    std::sort(std::begin(strings), std::end(strings), cmp);

    for (auto& s : strings)
        std::cout << s << "\n";
}

请注意,我冒昧地制作数组元素char*而不是char[]。 这是出于Carl Norum指出的原因。

答案 1 :(得分:1)

你没有交换字符串,你正在交换字符串的第一个字符。如果你想通过值传递,你需要像:

void swap(char **e1, char **e2) {
    char *tmp = *e1;
    *e1 = *e2;
    *e2 = tmp;
}

然后使用它:

swap(&words2Darray[curPos], &words2Darray[curPos-1]);

或者,您可以按原样保留swap来电并使用参考:

void swap(char *&e1, char *&e2) {
    char *tmp = e1;
    e1 = e2;
    e2 = tmp;
}

(我认为这是正确的 - 我的C ++生锈了。我会做一个测试以确定。)