请注意:我的 C++ 编程技能和术语充其量只是中级水平。所以请保持温柔 ;)。
我正在为一个大学类(class)研究一个多排序算法。最初,我构建的程序接收 20 个整数的数组,因为它与 .txt 文件一样大。最后一个实验室现在要求接收具有 10、100、1000、10000、100000 和 1000000 个不同数字的文件。我最初在 for 循环中使用 ifstream 来读取整数。现在我需要从文件中读取可变数量的整数,我遇到了这段代码的问题。我已经广泛搜索了这个网站和谷歌来找到这个问题的答案。我尝试了几十种不同的代码片段,但都无济于事。这是我目前正在运行的代码,适用于 20 个整数。
int i;
int A[20];
int length;
char unsortedFilename[200];
ifstream unsorted;
cout << "Please type the full name of the file you would like sorted.\n* ";
cin >> unsortedFilename;
unsorted.open(unsortedFilename);
length = (sizeof(A) / sizeof(*A));
for( i = 0; i < length; i++ )
{
unsorted >> A[i];
cout << A[i] << "\n";
}
insertionSort();
我确实混合了其他代码,但它是错误检查、重复数字删除的选择等。我希望这样的代码可以运行“i”次,其中“i”实际上是文件中的整数个数。另外,正如我之前提到的,我需要输入一个包含 1,000,000 个数字的文件。我不相信一个 int 数组能够容纳那么多数字。是否会像将我所有的整数交换为长整数一样简单?
感谢您提供的任何帮助。
最佳答案
按照评论中的建议,使用
std::vector<int>
而不是数组。而不是
for
循环,使用while
环形。突破while
当没有数字可读时循环。
while
循环:
std::vector<int> A;
int item;
while ( unsorted >> item )
{
A.push_back(item);
}
您可以对 std::vector
进行排序通过使用 std::vector::iterator
或者简单地通过 int*
访问数据由 A.data()
返回.
关于C++ 从 ifstream 创建一个可变大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26349067/