如何引用或调用在 c++ 中的其他 while 循环中创建的向量?

How to refer or call a vector that was created in other while loop in c++?

本文关键字:其他 while 循环 向量 创建 c++ 何引用 引用 调用      更新时间:2023-10-16

我正在尝试用C++编写一个小程序来测试插入排序和其他排序算法的性能。我想在 txt 文件中存储一个非常大的数字,让我的程序先读取它并将每个数字存储到一个向量中。因此,排序算法可以轻松处理此类向量。

但是我遇到了一个问题,我不知道如何在插入排序部分中调用 vector(num1(。由于向量在排序之前在 while 循环中初始化。编译器无法识别它,因此我的程序无法继续。因此,我希望有人给我一些建议来解决这个问题,或者谈谈您对我的代码的看法。非常感谢!

#include <iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int main() {
//To read file: 
ifstream num("test.txt");
char num_arry[1000000];
if (!num)
{
cout << "File load error,please check if file exist" << endl;
}
while (!num.eof())
{
num >> num_arry;
int number = stoi(num_arry); // convert char to int     
vector<int> num1;  //set a new vector to store file data numbers
num1.push_back(number); // push int in the vector
}
// Insertion sort start:
for (int i = 1; i < num1.size(); i++) {
int element = num1[i];
int j = i;
while (num1[j - 1] > element) {
num1[j] = num1[j - 1];
j = j - 1;
num1[j] = element;
}
}
for (int i = 0; i < num1.size(); i++) {
cout << num1[i] << " ";
}
return 0;
}

只需将vector<int> num1移动到while循环之前即可。这样,它就存在于该循环之外,特别是存在于下面要使用它的代码区域中。

即使范围在循环结束时幸存下来,您所拥有的在任何情况下都不起作用,因为向量在所述循环的每次迭代中都是重新创建的 - 它最终将成为一个只包含最后一个元素的向量。

换句话说,这个(简化形式(:

while (!num.eof()) {
vector<int> num1;
num1.push_back(something);
}
// Cannot see num1 here.

将变成:

vector<int> num1;
while (!num.eof()) {
num1.push_back(something);
}
// num1 is usable here.

您可能还需要重新考虑将您的号码加载到字符数组中,然后在其上调用stoi(除非您有特定原因这样做(。C++流的内容完全能够直接读取非字符数据类型,例如:

vector<int> numArray;
{
int number;
while (numInputStream >> number)
numArry.push_back(number);
}
相关文章: