Joh*_*ohn 0 c++ arrays function vector
初学者在这里试图理解函数的基本原理,传递我的引用和向量/数组.我的代码将大数据文件读入矢量.然后我不知何故需要将矢量转换为数组,对数组进行排序,并读取输出.我相信我的问题在于我尝试将矢量转换为数组.
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;
}
Run Code Online (Sandbox Code Playgroud)
您不需要将矢量转换为数组.您可以直接对矢量进行排序.
std::sort(values.begin(), values.end())
Run Code Online (Sandbox Code Playgroud)
有关排序的更多信息,请访问:http://www.cplusplus.com/reference/algorithm/sort/
我将补充说,一般来说,你永远不应该使用数组,特别是作为一个新的C++程序员.他们是多比矢量更复杂,并且在普通的C++代码几乎从来没有用.
http://www.parashift.com/c++-faq/arrays-are-evil.html
| 归档时间: |
|
| 查看次数: |
139 次 |
| 最近记录: |