新手编码器在这里: C++ 使用函数将向量复制到数组中

Novice Coder here: C++ Copying vector into array using functions

本文关键字:向量 复制 数组 函数 在这里 编码器 C++ 新手      更新时间:2023-10-16

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

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

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

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

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

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

const int SIZE = values.size();

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

int* arr = new int[size];

然后您还被迫手动删除数组。

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