新手编码器在这里: C++ 使用函数将向量复制到数组中
Novice Coder here: C++ Copying vector into array using functions
初学者在这里试图理解函数的基础知识,传递我的参考和向量/数组。我的代码将大型数据文件读入向量。然后,我需要以某种方式将向量转换为数组,对数组进行排序并读取输出。我相信我的问题在于我尝试将向量转换为数组。
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(),因为向量的元素是连续的。(对于其他容器则不然。
相关文章:
- 将指向给定子类的指针从一个向量复制到另一个向量
- 将字符向量复制到另一个向量
- 将shared_ptr的向量复制到抽象基的派生类
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 自定义类对象的C++向量 - 复制构造函数已删除 - std::ifstream
- 如何在C++中将一个对象从一个向量复制到另一个向量?
- 将特征向量复制到 C 数组
- 将std ::向量复制到CV :: Mat_的行操作相同
- 将向量复制到 std::string
- 如何以相反的顺序将整个向量复制到队列中
- 按索引将类类型元素从一个向量复制到另一个 c++
- 使用迭代器将向量复制到数组中
- 为什么是非法的:将指针向量复制到指向常量的指针向量中
- 将元素从一个向量复制到另一个向量的最有效方法,给定一个不被复制的索引列表
- C++-将数据从浮点向量复制到uint8向量
- 将字符串从向量复制到字符串
- 我可以使用STD ::复制将数据的位模式从整数向量复制到一系列未签名的字符
- 将指针从一个向量复制到另一个向量;地址指出了变化
- 如何将内容从一个字符串向量复制到另一个字符串向量
- 以相反的顺序将一个向量复制到另一个向量