【问题标题】:Reading arbitrary array of any size读取任意大小的任意数组
【发布时间】:2014-12-15 13:45:26
【问题描述】:

以下代码在读取两个包含两个 5X5 数组的 .txt 文件时可以正常工作。

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

    using namespace std;

    int main()
    {
        string myFile, mysecondFile, mystring;
        string DIR;
        string extension;
        int total = 0;

        int number_of_lines = 0;
        string line;

        extension = ".txt";
        DIR = "H:\\Year2\\EE273\\EE273\\Week6\\";

        cout << "Enter the name of the file: \t";
        cin >> myFile;
        cout << "Enter the name of the second file: \t";
        cin >> mysecondFile;

        myFile = DIR + myFile + extension;
        mysecondFile = DIR + mysecondFile + extension;

        ifstream inFile;
        ifstream inFile2;

    int i=5;
    int j=5;
    int i2=5;
    int j2=5;
    int i3=5;
    int j3=5;
    int k;
    int l;

int Array[5][5];
int Array2[5][5];
int Array3[5][5];
string attempt1,attempt2;
int row = 0;
int col = 0;
int row2 = 0;
int col2 = 0;//i = row
                    //y = column

inFile.open(myFile.c_str());


if (!inFile) {
    cout <<"Error opening file"<<myFile<<endl;
    return -1;
}

while (!inFile.eof())
{
    getline(inFile, attempt1);
    stringstream iss( attempt1 );
    string result;
    col = 0;
    while (getline( iss, result, ','))
    {
        //cout << result << endl;
        Array[row][col] = atoi(result.c_str());
        //j = j + 1;
        col = col + 1;

    }
    row = row + 1;
}
inFile.close();

inFile2.open(mysecondFile.c_str());
if (!inFile2) {
    cout <<"Error opening file"<<mysecondFile<<endl;
    return -1;
}
while (!inFile2.eof())
{
    getline(inFile2, attempt2);
    stringstream iss( attempt2 );
    string result2;
    col2 = 0;
    while (getline( iss, result2, ','))
    {   
        //cout << result2 << endl;
        Array2[row2][col2] = atoi(result2.c_str());
        col2 = col2 + 1;
    }
    row2 = row2 + 1;
}
inFile2.close();

/*for (int i=0;i<5;i++){
    for (int j=0; j<5; j++){
        cout<<Array[i][j]<<endl;}}
for (int i2=0;i2<5;i2++){
    for (int j2=0; j2<5; j2++){
        cout<<Array2[i2][j2]<<endl;
    }}

我在这里执行两个矩阵之间的乘法并将结果值写入第三个矩阵。

int Total=0;
i=0;
j2=0;
j=0;
j3=0;
for (i3=0; i3<5; i3++) {
    while(j3<5){
            while (j<5){
            for (i2=0;i2<5;i2++){
            Total += Array[i][j]*Array2[i2][j2];
            j++;
            Array3[i3][j3]=Total;

            }}
            j=0;
            j2++;
            j3++;
            Total=0;
            }
    i++;
    j=0;
    j2=0;
    j3=0;
    Total=0;
}

我的问题是:修改代码使其可以读取两个包含任意大小数组的 .txt 文件然后成功执行乘法的最简单方法是什么?

编辑我只能使用数组来做这件事,不幸的是我不能使用向量。

我认为涉及 new 运算符是否正确?

【问题讨论】:

  • 使用std::vector而不是裸数组。
  • 事情是这是一个评估,他们告诉我们只使用数组
  • 哎呀,你不认为你应该在你的帖子中包含这个限制吗?
  • @Paolokiller:所以写一些类似于std::vector 的东西(当它需要增长到超出其当前容量时重新分配和移动元素),然后使用它而不是裸数组。 (是的,这将涉及new 和delete。您还应该阅读Rule of Three。指针杂耍很棘手,这就是为什么我们有像vector 这样的友好图书馆设施来为我们管理它。)
  • @Paolokiller:您的意思是您不能将数组包装在一个为您管理它的好类中?这是一个相当奇怪的约束。但如果情况确实如此,只需在一大堆未封装的代码中做同样的事情(分配一个更大的数组、移动数据并删除旧的)。

标签: c++ arrays multiplication


【解决方案1】:

“最简单”的方法是做一些简单的事情,比如完全读取文件一次以获取行数/列数,然后再次读取文件以将值实际存储在矩阵中:

unsigned int rows = 0;
unsigned int cols = 0;

std::string line;
while (std::getline(inFile, line)) {
    rows++;
    std::stringstream ss(line);

    std::string col;
    while (std::getline(ss, col, ',')) {
        cols++;
    }
}

// Now allocate the rows*cols matrix
int** matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
    matrix[i] = new int[cols];
}

// and read your values into the matrix ...
// matrix[m][n] = xxx

两次读取文件效率非常低;还有其他方法可以预先获取大小。例如,您可以在输入文件中约定在数据之前包含矩阵宽度/高度:

[infile.txt]
3,3
1,2,3
4,5,6
7,8,9

现在您可以读取文件的第一行,并且您会知道该文件的其余部分包含一个 3x3 矩阵。使用new 分配您的矩阵(类似于上面的示例),然后继续将文件的其余部分读入其中。

记住使用delete[] 清理动态分配的矩阵。每次调用new 都应该调用一次delete。

for (int i = 0; i < rows; i++) {
    delete[] matrix[i];
}
delete[] matrix;

【讨论】:

  • 这正是我想要的。只要 getline 不断寻找值,那么行和列就会递增。我稍后会尝试该代码,但我相信它会很好地工作。为什么说效率低下?如果我们想打开内容未知的 .txt 文件,这不是最有效的解决方案吗?
  • @Paolokiller 做任何事情两次总是比做同样的事情一次要花费更多的时间。特别是,从磁盘读取文件通常是一项缓慢的操作,因此您需要避免冗余操作。在我的回答中,我包含了一种这样的方法:include the matrix width/height before the data :) 您也可以将文件存储为二进制文件并使用seekg() 和tellg() 确定大小,但这会带来其他复杂性(例如,不是人类可读)。如果允许,std::vector 也可以。解决方案之间总是需要权衡取舍。
【解决方案2】:

使用std::vector 代替原始数组。例如。您可以push_back 向量上的项目。更重要的是,您可以使用仅在运行时知道的大小来创建它,例如来自文件中的信息。

【讨论】:

  • 根据 OP 的评论,向量不能使用,因为它是一个赋值,并且他们被告知使用数组。
  • @Borgleader:是的,他在我发布这个答案后发布了这个。我不会追逐不断变化的需求。
  • 对信息做你想做的事,我只是提供它。无论如何,这是一个愚蠢的要求。
【解决方案3】:

最简单的方法要求文件包含矩阵的大小作为其第一个条目。有了这个,您可以回退到使用 C(C++ 不容忍动态大小的矩阵)并执行以下操作:

  1. 将矩阵的维度读入变量width和heigh。

  2. 使用分配矩阵

    int (*dynamicMatrix)[width] = malloc(height*sizeof(*dynamicMatrix));
    
  3. 重复使用您的代码来填充矩阵。

如果你不能回退到C,也不能使用std::vector&lt;&gt;,剩下的就是使用双指针:

int**dynamicMatrix = new int*[height];
for(size_t i = width; i--; ) dynamicMatrix[i] = new int[width];

同样,如果您可以在文件中定义前两个数字以包含文件中矩阵的宽度和高度,这是最简单的。如果您无法将这两个数字编码到您的文件中,则必须随时增加动态数组:

size_t lines = 0, allocatedLines = 8;
int** dynamicMatrix = new int*[allocatedLines];
while(/* can read a line */) {
    if(lines == allocatedLines) {
        int** temp = new int*[allocatedLines *= 2];
        for(size_t i = lines; i--; ) temp[i] = dynamicMatrix[i];
        delete[] dynamicMatrix;
        dynamicMatrix = temp;
    }

    //add one line
    size_t curLineLength = 0, allocatedLineLength = 8;
    dynamicMatrix[lines++] = new int[allocatedLineLength];

    //fill the line
    ...
}

用于重新分配行的类似块需要进入读取单行元素的循环。这很乏味;但要变得更好的唯一方法是使用不允许使用的东西。


顺便说一句:即使在 C 中重新分配的东西也更容易,因为它提供了 realloc() 函数:

size_t lines = 0, allocatedLines = 8;
int** dynamicMatrix = malloc(allocatedLines * sizeof(*dynamicMatrix));
while(/* can read a line */) {
    if(lines == allocatedLines) {
        //realloc takes care of copying the data to a new location (if that is necessary):
        allocatedLines *= 2;
        dynamicMatrix = realloc(dynamicMatrix, allocatedLines * sizeof(*dynamicMatrix));
    }

    //add one line
    size_t curLineLength = 0, allocatedLineLength = 8;
    dynamicMatrix[lines++] = malloc(allocatedLineLength * sizeof(**dynamicMatrix));

    //fill the line
    ...
}

由于没有与realloc() 等效的new/delete,因此您需要在C++ 中使用std::vector&lt;&gt;,或者按照上述方式自己进行复制。

【讨论】:

  • 我正在用 C++ 编写程序,所以我认为我不应该使用 malloc。我解决这个问题的最初想法是使用 getline 读入 txt 文件,并为行和列设置一个变量,这些变量根据正在读取的文件而增加。这有意义吗?我不知道该怎么做,但我想如果我能让程序知道文件中有多少行/列,我可以让其余的工作......
  • 我现在删除了对std::vector&lt;&gt; 的提及,并将其替换为没有它的情况下您需要在 C++ 中做什么的基本描述。希望对您有所帮助。
猜你喜欢
  • 2016-08-29
  • 1970-01-01
  • 2021-07-29
  • 2015-11-20
  • 1970-01-01
  • 2016-11-11
  • 2020-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多