用C++对数组进行排序

Sort an array in C++

本文关键字:排序 数组 C++      更新时间:2023-10-16

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

 #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;
}

您的交换错误。

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)你决定了它们是否只在上次测试中排序。

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