简体   繁体   English

在C / C ++中将矩阵读取为2D数组

[英]Read matrix to 2D array in C/C++

What is the simplest way to read/input a matrix of numbers into an array in C++? 在C ++中,将数字矩阵读/输入到数组中的最简单方法是什么?

This is the file content (dimensions are unknown): 这是文件内容(尺寸未知):

283 278 284 290 290 286 273 266 266 266 261 252 246
382 380 379 381 382 379 384 387 385 382 376 365 357 
285 282 281 279 276 273 272 264 255 255 247 243 237 
196 190 186 183 183 180 179 186 191 195 195 188 187 
245 237 226 220 221 222 225 228 234 245 252 264 272 
283 278 284 290 290 286 273 266 266 266 261 252 246

I've tried a lot of suggested codes, but non of them seem to work for me... :( I want to do the following with the matrix: 我已经尝试了很多建议的代码,但似乎都不适合我... :(我想对矩阵进行以下操作:

MATRIX[i][j] = MATRIX[i][j] + rand()-RAND_MAX/2;

What to include in the if loop to read the matrix?? 在if循环中包含哪些内容以读取矩阵?

#include <iostream>
#include <fstream>

ifstream pFile;
pFile.open("test.txt");

if (pFile.is_open())
{
    // SOMETHING HERE!!!!!??
}
else
{
    printf("Error reading the file!\n");
    return 1;
}

First, as others suggested, use a std::vector<std::vector<int>> . 首先,如其他建议一样,使用std::vector<std::vector<int>> It will make things a lot simpler. 它将使事情变得简单得多。

#include <vector>
typedef std::vector<int> IntVector;
typedef std::vector<IntVector> IntVector2D;

So our type is IntVector2D . 所以我们的类型是IntVector2D (I defined the one-dimensional vector to be used later) (我定义了一维矢量,以后将使用)

Next, we want to set up a loop that reads one line at a time, parses the line, and stores the int's found on the line in one row of the matrix. 接下来,我们要建立一个循环,一次读取一行,解析该行,并将在该行上找到的int存储在矩阵的一行中。 To do that, we can read the line into a string, and use istringstream to do the parsing. 为此,我们可以将行读入字符串,然后使用istringstream进行解析。

Last, for each line stored, we apply the changes to each item on the row according to your random number function. 最后,对于存储的每一行,我们根据您的随机数函数将更改应用于行中的每个项目。

So here is a sample of all of this put together: 因此,这是所有这些的汇总示例:

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

typedef std::vector<int> IntVector;
typedef std::vector<IntVector> IntVector2D;

using namespace std;

// random number function to apply
int ApplyRand(int num)
{ return num + rand() - RAND_MAX/2; }

void OutputMatrix(const IntVector2D& m)
{
    cout << "\n";
    IntVector2D::const_iterator it = m.begin();
    while (it != m.end())
    {
        copy(it->begin(), it->end(), ostream_iterator<int>(cout, " "));
        cout << "\n";
        ++it;
    }
}

// Transform the numbers in the matrix
void TransformMatrix(IntVector2D& m)
{
    IntVector2D::iterator it = m.begin();
    while (it != m.end())
    {
        transform(it->begin(), it->end(), it->begin(), ApplyRand);
        ++it;
    }
}

int main()
{
    IntVector2D matrix;
    ifstream pFile("test.txt");
    string s;

    while ( std::getline(pFile, s) )
    {
        // create empty row on back of matrix
        matrix.push_back(IntVector());
        IntVector& vBack = matrix.back();

        // create an istringstream to parse
        istringstream ss(s);

        // parse the data, adding each number to the last row of the matrix
        copy(istream_iterator<int>(ss), istream_iterator<int>(), back_inserter(vBack));
    }
    // output the matrix
    OutputMatrix(matrix);

    // Apply rand to each number
    TransformMatrix(matrix);

    // output the updated matrix 
    OutputMatrix(matrix);
}

Output: 输出:

283 278 284 290 290 286 273 266 266 266 261 252 246
382 380 379 381 382 379 384 387 385 382 376 365 357
285 282 281 279 276 273 272 264 255 255 247 243 237
196 190 186 183 183 180 179 186 191 195 195 188 187
245 237 226 220 221 222 225 228 234 245 252 264 272
283 278 284 290 290 286 273 266 266 266 261 252 246

-16059 2362 -9765 10407 3076 -373 -4632 13241 10845 8347 -10417 12014 7144826 
-6042 -15513 -13007 -4059 -11177 -10563 16395 -1394 -12099 -15854 -15726 -3644
1323 2615 3616 3791 -10660 5616 -1340 -4581 -14259 3784 9531 10159 889
-6293 12510 7614 15122 14133 1470 -11540 -1056 -8481 12065 -9320 9352 11448
16524 16611 3880 -3304 -7439 -6420 11371 -15377 -3833 -13103 6059 -14277 -15823
14006 -7065 -7157 3171 6555 11349 7695 -227 -9388 8253 -772 -1125 14964

Note the use of std::copy to extract the items from the istringstream , and back_inserter , which is responsible for calling push_back on the last row of the matrix. 请注意使用std::copyistringstreamback_inserter提取项目,后者负责在矩阵的最后一行调用push_back

Also, the usage of std::transform allows us to call a function on each element, "transforming" the element from the original value to the changed value using ApplyRand as the function to do this transformation. 同样,使用std::transform允许我们在每个元素上调用一个函数,使用ApplyRand作为执行此转换的函数,将元素从原始值“转换”为更改后的值。

Here's a simple way to read in a matrix of unknown size using vectors. 这是一种使用向量读取大小未知的矩阵的简单方法。 The advantage of vectors over arrays if you don't know the dimensions that you're working with is that you don't need to worry about resizing your data structure if you run out of space. 如果不知道要使用的维数,则向量比数组的优势在于,如果空间不足,则无需担心调整数据结构的大小。

    std::vector<std::vector<int> > matrix;
    std::string line;
    int value;

    // read in matrix
    std::ifstream file("path/to/file.txt");
    while(std::getline(file, line)) {
            std::vector<int> row;
            std::istringstream iss(line);
            while(iss >> value){
                    row.push_back(value);
            }
            matrix.push_back(row);
    }

First of all, we declare a vector of vectors to keep our matrix in. Note that the advantage of vectors over arrays if you don't know the dimensions that you're working with is that you don't need to worry about resizing your data structure if you run out of space. 首先,我们声明一个向量vectors以保持矩阵在其中。请注意,如果您不知道要使用的维数,向量相对于数组的优势是您无需担心调整大小数据结构(如果空间不足)。 This is why we use vectors instead of arrays. 这就是为什么我们使用向量而不是数组的原因。 After that, we use stringstream to read all integers from input. 之后,我们使用stringstream读取输入中的所有整数。 In a while loop, we continue until there still exits another line (getline() returns true if there is no more lines). 在while循环中,我们继续进行,直到仍然退出另一行为止(如果没有更多行,则getline()返回true)。 In each step, we read a line from input (no matter how long it is, we read it completely) then we seprate the line's integers and put them in a vector using string stream. 在每个步骤中,我们从输入中读取一行(无论它有多长,我们都会完整地读取它),然后分离出行的整数,并使用字符串流将它们放入向量中。 Then, we add that vector to our matrxi 2D vector. 然后,将该向量添加到我们的Matrxi 2D向量中。 I wrote this code: 我写了这段代码:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>
using namespace std;

int main () {

    fstream cin;
    cin.open("input.txt");

    string s;
    vector <vector <int> > matrix;

        while (getline(cin, s)) {

        stringstream input(s);

        int temp;
        vector <int> currentLine;
        while (input >> temp)
            currentLine.push_back(temp);

        matrix.push_back(currentLine);

        }

        for (unsigned int i = 0; i < matrix.size(); i++) {
            for (unsigned int j = 0; j < matrix[i].size(); j++)
                cout << matrix[i][j] << " ";
            cout << endl;
        }

    return 0;
}

And the output is exactly what you want. 输出正是您想要的。 Note that the first line can't be seen and I had to scroll up to see that but be sure it's there. 请注意,第一行看不到,我不得不向上滚动才能看到,但请确保它在那里。 Give it a try. 试试看。 Here's the output: 这是输出: 在此处输入图片说明

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

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