【问题标题】:Sort an array in C++在 C++ 中对数组进行排序
【发布时间】:2013-12-24 18:57:38
【问题描述】:

问题我从用户那里得到了 5 个名字并按字母顺序显示它们。这是我的代码。调试时,问题似乎出在 sorted 函数中。它应该告诉我数组何时完全排序。有人可以告诉我我的问题在哪里。谢谢

 #include<iostream>
#include<string>
using namespace std;
void swap(string,string);
bool sorted (string [3]);

void main ()
{
    string firstname[3];
    string sortfirstname[3];
    int orginialindex[3];
    string lastname[3];
    float gpa[3];
    int id[3];
    for (int i=0;i<3;i++)
    {
    cout<<"Enter firstname"<<endl;
    cin>>firstname[i];
    }
    for (int i=0;i<3;i++)
    {
        sortfirstname[i]=firstname[i];
    }
    while (!(sorted(sortfirstname)))
    {
    for (int i=0;i<3;i++) //3-2-1
    {
        if (sortfirstname[i]>sortfirstname[i+1])
        {
            swap(sortfirstname[i],sortfirstname[i+1]);
        }
    }
    }
    cout<<sortfirstname[0]<<sortfirstname[1]<<sortfirstname[2];
}

void swap (string a, string b)
{
    string temp = b;
    b = a;
    a = temp;
}

bool sorted (string sortfirstname[3])
{
    bool sort;
    for (int i=0;i<3;i++)
    {
        if (sortfirstname[i]<sortfirstname[i+1])
            sort = true;
        else
            sort = false;
    }
    return sort;
}

【问题讨论】:

标签: c++ arrays sorting


【解决方案1】:

你的交换是错误的。

void swap (string a, string b)
{
    string temp = b;
    b = a;
    a = temp;
}

这不会做任何事情! 您需要采用参考参数,即将函数签名更改为:

void swap (string& a, string& b)

另外,bool sorted (string sortfirstname[3]) 有错误,试试:

bool sorted (string sortfirstname[3]) {
    bool sort = true;
    for (int i=0;i<3-1;i++)
    {
        if (sortfirstname[i]>sortfirstname[i+1])
            sort = false;
    }
    return sort;
}

这是正确的两件事。 (a)你之前跑完了,(b)你决定它们是否在最后一次测试中专门排序。

【讨论】:

    【解决方案2】:

    for 循环退出条件应为 i&lt;3-1,因为稍后您将访问第 (i+1) 个元素。

    【讨论】:

      猜你喜欢
      • 2011-04-23
      • 2013-08-05
      • 2021-11-18
      • 1970-01-01
      • 2018-04-20
      • 2012-04-25
      • 2011-04-25
      • 1970-01-01
      相关资源
      最近更新 更多