C ++读取矩阵类型从文件输入

问题描述 投票:2回答:1

C++中,有可能从文件中读取NxN矩阵样式输入并将其分配给二维数组,其时间渐近复杂度优于O(n^2),假设N在第一行中给出,而其他行在整数之间有空格?我可以逐个填充我的数组遍历输入整数,其成本为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);
   }
}

我只是想像读取nth line并创建数组(或某个容器)的nth row,这将减少linear time的时间复杂度。是否有任何实现比迭代给定矩阵的所有元素更好?

c++ input time-complexity ifstream
1个回答
1
投票

循环通过O(N)的答案,其中N是一个int,但是就线而言,无论如何,你总是有O(N ^ 2)。也许这是您可以拥有的最接近的解决方案。

int temp;
int countX = 0;
while(inFile >> temp)
{
    A[countX/size][countX % size] = std::stoi(temp);
    countX++;
}

我希望这有帮助。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.