如何引用或调用在 c++ 中的其他 while 循环中创建的向量?
How to refer or call a vector that was created in other while loop in c++?
我正在尝试用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);
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- while循环中while循环的时间复杂度是多少
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 在其他文件中创建类时在 c++ 项目中不起作用
- 擦除while循环中迭代的元素
- 类与私有变量的其他类之间的线程安全性
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 为什么我的 while 循环对于特定输入中断,而对于其他输入工作正常?
- 如何引用或调用在 c++ 中的其他 while 循环中创建的向量?
- 从while循环(c++)中断后,似乎没有其他代码执行
- 如何停止 while 循环并转到我的其他语句
- C++Bare布尔表达式(不包含if、while或其他语句)
- 这个 while 循环执行其适当的功能,但对于其他内容是必需的