简体   繁体   English

如何输入矩阵样式的txt文件而不是为C ++定义我自己的int 2D数组

[英]How to input an matrix style txt file instead of defining my own int 2D array for C++

So I'm pretty new to C++ but i think im gettting the hang of it a bit. 因此,我对C ++相当陌生,但我认为我有点不了解它了。

As part of an excersize, I have to take an input text file and apply this in a "shortest distance algorithm" where ultimatly I want to output all the shortest distances and routes but i haven't gotten that far yet. 作为练习的一部分,我必须输入一个文本文件并将其应用到“最短距离算法”中,最终我想输出所有最短的距离和路线,但我还没有走那么远。 I have used the Floyd Warshall algorithm. 我已经使用了Floyd Warshall算法。 For now my question is, how do i replace a self written int array by a text input. 现在我的问题是,如何用文本输入替换自写的int数组。 the input array is just numbers but actually represents distances between nodes. 输入数组只是数字,但实际上表示节点之间的距离。 The test array that im using now only has 3 nodes, but i want to be able to expand it to a much larger node amout, say 100. 我现在使用的测试阵列只有3个节点,但我希望能够将其扩展到更大的节点,例如100。

example test matrix: 测试矩阵示例:

0 1234567 100 0 1234567 100

1234567 0 400 1234567 0 400

100 400 0 100 400 0

Should be read as: 应理解为:

           node1      node2       node3
  node 1    0          999999     100
  node 2   999999       0         400
  node 3    100        400         0 

The large numbers: 999999 represents a distance that is too large too count as a edge. 大数字:999999表示距离太大,因此不能算作边缘。

As of now my code looks something like this: 到目前为止,我的代码如下所示:

#include<stdio.h>

// Number of vertices
#define V 3

// Define 999999 as a distance that is too large to represent a edge connection
#define TooLarge 999999

// The print function
void printSolution(int dist[][V]);

        // Distance algorithm
    void Distance (int distgraph[][V])
    {
        // output matrix that will have the shortest distance for every vertice
        int dist[V][V], i, j, k;

        // initial values for shortest distance are based on shortest paths.
        for (i = 0; i < V; i++)
            for (j = 0; j < V; j++)
                dist[i][j] = distgraph[i][j];

        // Add all vertices to the set of intermediate vertices.
             for (k = 0; k < V; k++)
        {
            // use all vertices as seperate source
            for (i = 0; i < V; i++)
        {
            // use all vertices as destination for the earlier determined source

            for (j = 0; j < V; j++)
            {
                // If vertex k is on the shortest path from i to j, then update the value of dist[i][j]
                if (dist[i][k] + dist[k][j] < dist[i][j])
                    dist[i][j] = dist[i][k] + dist[k][j];
            }
        }
    }

    // Print the shortest distance matrix
    printSolution(dist);
}

// The print function
void printSolution(int dist[][V])
{
    printf ("Shortest distance matrix \n");
    for (int i = 0; i < V; i++)
    {
        for (int j = 0; j < V; j++)
        {
            if (dist[i][j] == 999999)
                printf("%7s", "TooLarge");
            else
                printf ("%7d", dist[i][j]);
        }
        printf("\n");
    }
}

// driver program to test above function
int main()
{
      int distgraph[V][V] = { {0, 1234567, 100},
                              {1234567, 0, 400},
                              {100, 400, 0,},
                            };

    // Print the solution
    Distance(distgraph);
    return 0;
}

Hopefully someone can help me, I have the feeling im just forgetting something stupid. 希望有人能帮助我,我觉得我只是忘记了一些愚蠢的事情。 I have tried to inport the textfile using this type of code: 我尝试使用这种类型的代码导入文本文件:

    using namespace std;

double distances [3][3];

int main () {
  int x, y;
  ifstream in("citytest.txt");

  if (!in) {
    cout << "Cannot open file.\n";
    return 0;
  }

  for (y = 0; y < 3; y++) {
    for (x = 0; x < 3; x++) {
      in >> distances[x][y];
    }
  }
    cout << distances[3][3] << " " << endl;
      in.close();

Which i know works, but only inports a predetermind part of the matrix whereas i want to input the entire array. 我知道这是可行的,但是只导入矩阵的预定部分,而我想输入整个数组。 (the cout function is just there to test if the correct distances were given as an input) (cout函数仅用于测试是否输入了正确的距离)

You cannot efficiently allocate the container unless you know big the workload in your external data file is. 除非您知道外部数据文件中的工作量很大,否则您将无法有效地分配容器。

Thus: 从而:

  • tokenize the first line of your file and take the dimension N from that 标记文件的第一行,并从中获取维度N
  • allocate your container accordingly 相应地分配您的容器
  • then consume the rest of the file and put the data into the container; 然后使用文件的其余部分并将数据放入容器中; maybe throw if a row's length doesn't match N, or if there are not N rows. 如果某行的长度不匹配N,或者没有N行,则可能throw该错误。

You may consider that 您可能会认为

  • representing a graph by a full adjacency matrix is a debatable concept; 用完整的邻接矩阵表示图是值得商a的概念; it's space-inefficient and time-inefficient for sparse graphs 稀疏图的空间效率低且时间效率低
  • a 2D c-array is not the only possible representation of a matrix; 二维c阵列不是矩阵的唯一可能表示;而是二维矩阵。 you may consider a flat std container and implement a slice -style access on it 您可以考虑使用扁平的std容器,并在其上实现切片式访问
  • last not least you may want to have a look at boost::graph 最后,您可能需要看一看boost :: graph

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM