0

初学者在这里试图理解函数的基础知识,传递我的参考和向量/数组。我的代码将一个大数据文件读入一个向量。然后,不知何故,我需要将向量转换为数组,对数组进行排序,然后读取输出。我相信我的问题在于我尝试将向量转换为数组。

using namespace std;


//function prototype
int readInput(vector<int> &vect);
void sort(int[], int);
void showArray(int[], int);



int main()
{
vector<int> values;
int sum, avg;

sum = readInput(values);

const int SIZE = values.size(); //ISSUE LIES HERE
int arr[SIZE]; //and here 

sort(arr, SIZE);
showArray(arr, SIZE);


avg = sum / values.size();
//cout << "The average is: " << avg;

return 0;
}

int readInput(vector<int> &vect)
{

int count;
int total = 0;

ifstream inputFile("TopicFin.txt"); //open file

if(!inputFile)
{
    return 0; // if file is not found, return 0
}

while(inputFile >> count) //read file
 vect.push_back(count); //add to file

for (int count = 0; count < vect.size(); count++)
 total+=vect[count]; //sum data in vector

return total;

}

void sort(int 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;
}
}

void showArray(const int array[], int size)
{
for(int count = 0; count < size; count++)
    cout << array[count] << " " << endl;

}
4

3 回答 3

5

您不需要将向量转换为数组。您可以直接对向量进行排序。

std::sort(values.begin(), values.end())

有关排序的更多信息:http ://www.cplusplus.com/reference/algorithm/sort/

我要补充一点,一般来说,你永远不应该使用数组,尤其是作为一个新的 C++ 程序员。它们向量复杂得多,并且在普通的 C++ 代码中几乎没有用处。

http://www.parashift.com/c++-faq/arrays-are-evil.html

于 2013-11-07T18:51:40.033 回答
3

让我先说一下,虽然这对于学习来说是一件好事,但在实际代码中可能不应该将向量转换为数组。实际上,您会使用std::sort对向量进行排序。

问题的根源是您无法使用int arr[SIZE]语法声明在编译时未知的大小数组。

const int SIZE = values.size();

this 的值在代码执行时是已知的,但在编译时不知道。因此int arr[SIZE];,不能像说一样工作int arr[100]。要声明一个您在运行时知道其大小的数组,您可以像这样动态地执行它

int* arr = new int[size];

然后你也被迫手动删除数组。

于 2013-11-07T18:54:54.520 回答
0

正如 seanmcl 所说,您无需转换为数组即可进行排序。但是,如果您想做的是编写排序函数的练习,那么您可以简单地使用 values.begin() 因为向量的元素是连续的。(这不适用于其他容器。)

于 2013-11-07T18:56:10.653 回答