I am trying to write a small program in C++ to test the performance of insertion sort and other sorting algorithms. I would like to store a very large numbers in a txt file and let my program read it first and store each number into a vector. So the sorting algorithms could easily handle such vector.
But I came across an issue, that I don't know how to call the vector(num1) in my insertion sort part. As the vector was initialized in a while loop prior to the sorting.The compiler cannot identify it so my program can not proceed. So I would appreciate anyone to give me some advice to solve this issue or maybe give your thoughts about my codes. Thanks very much!
#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;
}