C++ Selection Sort of an Array of String Objects

眉间皱痕 提交于 2019-12-24 20:25:22

问题


I'm trying to implement a selection sort function for an array of user inputted string objects. Am I on the right path as far as arguments go. Thanks

void selectionSort(char ARRAY[], int size)
{
int startScan, minIndex, minValue;

for (startScan = 0; startScan < (size - 1); startScan++)
{
    minIndex = startScan;
    minValue = ARRAY[startScan];
    for (int index = startScan + 1; index < size; index++)
    {
        if (ARRAY[index] < minValue)
        {
            minValue = ARRAY[index];
            minIndex = index;
        }
    }
    ARRAY[minIndex] = ARRAY[startScan];
    ARRAY[startScan] = minValue;
}
}

回答1:


You probably want to use the STL libabry and declare the argument as

std::vector< std::string >

then the sort function will work directly, like this

std::vector< std::string > array;
std::sort (array.begin(), array.end());



回答2:


If you are sorting string objects then there's a lot of problems. The code you wrote sorts characters. This:

char ARRAY[]

is an array of characters. These:

char *ARRAY[]
std::string ARRAY[]

are arrays of strings. You will have to change your function appropriately with either of these.



来源:https://stackoverflow.com/questions/7465647/c-selection-sort-of-an-array-of-string-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!