繁体   English   中英

如何读取文件并将其存储为矩阵(二维数组)?

[英]How do I read a file and store it as a Matrix (2D aray)?

我有一个图形着色程序,它将二维数组作为邻接矩阵,并根据该邻接矩阵为图形着色。 这个文件是Color.cpp 我有另一个程序来创建这个邻接矩阵并将它放在一个文本文件中,这个程序AdjacencyMatrix.cpp

当我最初创建着色程序时,我将邻接矩阵硬编码到二维数组graph[V][V] ,其中 V 是顶点数。

这是两个独立的程序,我只是将AdjacencyMatrix.cpp创建的邻接矩阵复制并粘贴到Color.cpp

因为我的程序已经创建了一个包含邻接矩阵的文件,所以我想让我的着色程序读取该文件。 我知道最好的做法是将它们组合起来,并将存储在数组中的矩阵通过一个内聚程序传递给着色程序。 我认为在这一点上读取文件是我最简单的解决方案,但是如果有更多有经验的用户可以向我展示如何将矩阵存储在数据结构中并将其传递给着色程序,我欢迎它。

邻接矩阵.cpp

该程序接收一个文件,该文件是一个作为相邻对列出的整数字符串,并从中创建一个邻接矩阵,然后将其存储在一个文件中。 文件“24cell_skeleton.txt”是它读入的文件,“out.txt”是它打印矩阵的文件。

#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;
const int cellSize = 24;
bool graph[cellSize][cellSize];
int prevNum = -1;
int currNum = -1;


bool markMatrix(int x, int y) {
graph[x][y] = true;
graph[y][x] = true;
/*std:cout << "adding pair: " << y << "," << x << "\n";*/
return true;

}

int main()
{

ifstream in("C:\\Users\\Austin\\Documents\\adjMatrix\\24cell_skeleton.txt");
ofstream out;
out.open("C:\\Users\\Austin\\Documents\\adjMatrix\\output.txt", ios::out);
ios::out;

string line, field;

vector< vector<string> > array;  // the 2D array
vector<string> v;                // array of values for one line only

while (getline(in, line))    // get next line in file
{
    v.clear();
    stringstream ss(line);

    while (getline(ss, field, ','))  // break line into comma delimited fields
    {
        v.push_back(field);  // add each field to the 1D array
    }

    array.push_back(v);  // add the 1D array to the 2D array
}

// print out what was read in
bool firstIter = true;

for (size_t i = 0; i<array.size(); ++i)
{
    for (size_t j = 0; j<array[i].size(); ++j)
    {
        string curr = array[i][j]; // (separate fields by |)
        prevNum = currNum;
        currNum = stoi(curr);

        if (j != 0 && firstIter) { //if its not the first iteration . . . or the last?
                                   /*out << "adding pair: " << prevNum << "," << currNum << "\n";*/
            markMatrix(prevNum, currNum);
        }
    }
    firstIter = false;

}

in.close();


//std::cout << "{";
for (int i = 1; i <= cellSize; ++i)
{
    std::cout << "{";
    out << "{";
    for (int j = 1; j <= cellSize; ++j)
    {
        //std::cout << "{";
        std::cout << graph[i][j] << ' ';
        std::cout << ", ";
        out << graph[i][j] << ' ';
        out << ", ";
        //std::cout << "}";
    }
    out << "},";
    std::cout << "},";
    std::cout << std::endl;
}

//std::cout << "}";

out.close();
//cout << graph[534][42];

system("pause");
return 0;

}

颜色文件

该文件为给定邻接矩阵的图形着色。 就像我之前提到的,矩阵被硬编码到其中(从上一个程序创建的文件中复制和粘贴)。 这是我想阅读文件而不是自己复制和粘贴的地方。

#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <fstream>
#include<stdio.h>
#include<cstdio>


// Number of vertices in the graph
#define V 24

using namespace std;

//this function was added in the update to attempt reading file and storing into a 2d matrix

int createMatrix(int myArray[V][V]) 
{
  ifstream in("C:\\Users\\Austin\\Documents\\adjMatrix\\output.txt");

  for (int i = 0; i < V; i++)
  {
    for (int j = 0; j < V; j++)
    {
        in >> myArray[i][j];
    }
  }
return myArray[V][V];
}
//end of updated code added

void printSolution(int color[]);

/* A utility function to check if the current color assignment
is safe for vertex v */
bool isSafe(int v, bool graph[V][V], int color[], int c)
{
for (int i = 0; i < V; i++)
    if (graph[v][i] && c == color[i])
        return false;
return true;
}

/* A recursive utility function to solve m coloring problem */
bool graphColoringUtil(bool graph[V][V], int m, int color[], int v)
{
/* base case: If all vertices are assigned a color then
return true */
if (v == V)
    return true;

/* Consider this vertex v and try different colors */
for (int c = 1; c <= m; c++)
{
    /* Check if assignment of color c to v is fine*/
    if (isSafe(v, graph, color, c))
    {
        color[v] = c;

        /* recur to assign colors to rest of the vertices */
        if (graphColoringUtil(graph, m, color, v + 1) == true)
            return true;

        /* If assigning color c doesn't lead to a solution
        then remove it */
        color[v] = 0;
    }
}

/* If no color can be assigned to this vertex then return false */
return false;
}

bool graphColoring(bool graph[V][V], int m)
{
// Initialize all color values as 0. This initialization is needed
// correct functioning of isSafe()
int *color = new int[V];
for (int i = 0; i < V; i++)
    color[i] = 0;

// Call graphColoringUtil() for vertex 0
if (graphColoringUtil(graph, m, color, 0) == false)
{
    std::cout << "Solution does not exist";
    return false;
}

// Print the solution
printSolution(color);
return true;
}

/* A utility function to print solution */
void printSolution(int color[])
{
std::cout << "Solution Exists:"
    " Following are the assigned colors \n";
for (int i = 0; i < V; i++)
    std::cout << color[i];
std::cout << "\n";
}

// driver program to test above function
int main()
{

/* Create following graph and test whether it is 3 colorable
(3)---(2)
| / |
| / |
| / |
(0)---(1)
*/
bool graph[V][V] = {
    { 0 , 1 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 0 , 1 , 1 , 0 , 0 , },
    { 1 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 0 , 0 , },
    { 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 1 , },
    { 1 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , },
    { 1 , 0 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 1 , 1 , },
    { 0 , 1 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 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0 , 0 , 0 , 1 , 1 , 0 , 1 , 1 , },
    { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , },
    { 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , },
    { 1 , 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , },
    { 0 , 0 , 1 , 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , },
    { 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , },
    { 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 1 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , },
    { 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , },
    { 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , },
};
int m = 5; // Number of colors
graphColoring(graph, m);
//return 0;

system("pause");
}

有没有办法从文件中获取这个矩阵而不是将它硬编码到程序中? 方括号和逗号很容易在文件中添加或删除。 当硬编码到着色程序中时,它们是必需的,但如果我可以从文件中读取它们,我认为它们不是必需的。

为了尽可能清楚地说明这一点,您在Color.cpp看到 24x24 矩阵的Color.cpp ,我希望该部分是从AdjacencyMatrix.cpp创建的 out.txt 中读取的矩阵。

编辑/更新

到目前为止,我在color.cpp的开头有color.cpp

int createMatrix(int myArray[V][V]) 
{
  ifstream in("C:\\Users\\Austin\\Documents\\adjMatrix\\output.txt");

  for (int i = 0; i < V; i++)
  {
    for (int j = 0; j < V; j++)
    {
        in >> myArray[i][j];
    }
  }
return myArray[V][V];
}

我知道这里有些东西,但如果我能让它工作,我计划使用类似的东西

bool graph[V][V] = 
{ 
    myArray[V][V]
};

main()

截至目前,VisualStudio 表示myArray是一个未声明的标识符,并且在main()未定义。

你的createMatrix函数就createMatrix ,但是return myArray[V][V]; 不是你想做的。 这就是说返回一个超出数组边界的int (大小为 V 的数组在 0 到 V-1 之间有效。未定义行为不良将因违反数组边界而导致。

幸运的是,您不必返回该死的东西。 myArray是一个指向调用createMatrix的数组的指针(参见什么是数组衰减? ),所以in >> myArray[i][j]; 正在将文件直接读入数组。

因此,通过一些检查以确保读取成功:

bool createMatrix(int myArray[V][V]) 
{
    ifstream in("C:\\Users\\Austin\\Documents\\adjMatrix\\output.txt");
    if (in) // if the file is open and readable
    {
        for (int i = 0; i < V; i++)
        {
            for (int j = 0; j < V; j++)
            {
                if (!(in >> myArray[i][j]))
                { // failed to read a value from the file. Bad file
                    // may want to log the error here so you know why it failed
                    return false;
                }
            }
        }
    }
    else
    { // couldn't open the file
        // may want to log the error here so you know why it failed
        return false;
    }
    return true; // read everything we wanted to read. all done.
}

然后在main

int main()
{
    int graph[V][V];
    if (createMatrix(graph)) 
    { // read the file successfully
        int m = 5; // Number of colors
        graphColoring(graph, m);
    }
    else
    { // did not read the file successfully
         // display failure message
    }
    system("pause");
}

暂无
暂无

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

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