In C++
is it possible to read a NxN
matrix style input from a file and assign it to a two dimensional array in a time that has asymptotic complexity better than O(n^2)
assuming that N
is given in the first line and other lines has a whitespace between integers ? I can fill my array with one by one traversing the input integers which has a cost O(n^2)
.
#define MAX_SIZE 1000
std::string row,temp;
std::ifstream inpfile("input.txt");
inpfile>>row;
int size=std::stoi(row);
static int M[MAX_SIZE][MAX_SIZE];
for(int i=0;i<size;++i){
for(int j=0;j<size;++j){
inpfile>>temp;
A[i][j]=std::stoi(temp);
}
}
I just think something like reading the nth line
and creating the nth row
of array (or some container) which will reduce time complexity to linear time
. Are there any implementations better than iterating all elements of given matrix ?
An answer which loop through O(N) where N is an int would be this however in terms of lines you will always have O(N^2) regardless. Perhaps this is the closest solution you could have.
int temp;
int countX = 0;
while(inFile >> temp)
{
A[countX/size][countX % size] = std::stoi(temp);
countX++;
}
I hope this helps.