按字母顺序排列的字符串

时间:2014-08-22 16:19:41

标签: c++ string sorting loops

我试图使用递归函数按字母顺序打印字符串,但它给出了字符串下标超出范围错误。

string alpha(string word)
{
    char temp;
    int count = 0;
    int i = 0;

    while (count < word.size())
    {
        if (word[i] > word[i + 1])
        {
            temp = word[i];
            word[i] = word[i + 1];
            word[i + 1] = temp;
            i++;
            if (i >= word.size())
            {
                alpha(word);
            }
        }
        else
        {
            count++;
        }
    }
    return word;
}

2 个答案:

答案 0 :(得分:1)

因为您使用if (word[i] > word[i + 1]),所以必须在结束之前停止循环...并且您需要counti(不是两者);

while (i + 1 < word.size()) // <-- like so

或者您可以使用

int i = 1;
while (i < word.size()) {
  if (word[i - 1] > word[i]) {

答案 1 :(得分:0)

我会这样做:

std::string alpha(std::string s)
{
    std::sort(s.begin(), s.end());
    return s;
}

Demo

如果您想自己实施O(n²)排序算法,可以这样做:

std::string alpha(std::string word)
{
    for (std::size_t i = 0; i != word.size(); ++i) {
        for (std::size_t j = i + 1; j != word.size(); ++j) {
            if (word[j] < word[i]) {
                std::swap(word[i], word[j]);
            }
        }
    }
    return word;
}

或者是一个反复的人:

std::string alpha(std::string word)
{
    auto it = std::is_sorted_until(word.begin(), word.end());

    if (it == word.end()) {
        return word;
    }
    std::size_t i = std::distance(word.begin(), it);
    do {
        std::swap(word[i], word[i - 1]);
        --i;
    } while (i > 1 && word[i] < word[i - 1]);
    return alpha(word);
}
相关问题