尝试对对象数组进行排序时程序终止

Hel*_*uin 2 c++ arrays sorting

我有一个class被叫ContactInfo,其结构如下:

class ContactInfo
{
    private:
        string contactName;
        string contactNumber;

        public:
            ContactInfo()
            {
                contactName = "";
                contactNumber = "";
            }
            //setter and getters
};
Run Code Online (Sandbox Code Playgroud)

我有一个函数,ContactInfo通过用户输入创建一个数组并填充它.填充数组后,它将被传递给另一个将它排序的函数,所述函数编写如下所示.

void sortListByName(ContactInfo contactList[], int listSize)
{
    for(int i = 0; i < listSize; i++)
    {
        for(int j = i+1; j < listSize+1; j++)
        {
            if(contactList[i].getContactName() > contactList[j].getContactName())
            {
                ContactInfo temp = contactList[j];
                contactList[i] = contactList[j];
                contactList[j] = temp;
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

主要方法

int main()
{
    ...

    int n;//array size
    ContactInfo *newList = contactList(n);//populates the array.
    sortListByName(newList, n);

    ...
}
Run Code Online (Sandbox Code Playgroud)

问题是程序会在排序发生之前终止并产生错误:

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid
Run Code Online (Sandbox Code Playgroud)

Pau*_*ger 5

查看内循环的上限.请注意,我们可以j等于最后一次迭代的数组大小.

在C++中,大小数组的N元素索引0N-1.在您的情况下,您尝试访问超出数组末尾的元素,并且正在运行未定义的行为.确保索引在数组的范围内.

其次,你应该尽可能地使用std :: vector而不是原始数组.

第三,标准库为您提供std :: sort算法,它几乎总是比您实现的冒泡排序更快.