Keresés

Új hozzászólás Aktív témák

  • b.kov

    senior tag

    válasz #74220800 #3893 üzenetére

    Üdv!
    Nem egy kezdőszelet, de ha tanulod a nyelvet, előbb-utóbb úgyis el fogod hagyni a tömböket valószínűleg, és helyette stl konténereket, és algoritmusokat fogsz használni.

    Itt van egy gyors szösszenet C++11-es módszerrel a problémádra:

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

    // Returns a matrix (N x M), storing read data from file
    std::vector<std::vector<int32_t>> readData(std::string fileName)
    {
    // Open file
    std::ifstream input;
    try
    {
    input.open(fileName);
    }catch(std::ios_base::failure& e)
    {
    std::cerr << e.what() << std::endl;
    return std::vector<std::vector<int32_t>>();
    }

    std::string line; // For reading line by line
    input >> line; // Reading N
    std::vector<std::vector<int32_t>> result(std::stoi(line)); // Returnable vector

    std::getline(input, line); // Reading M, but do not store

    // Write from file to matrix
    for(auto& matrixLine : result)
    {
    std::getline(input, line);
    std::istringstream stringOfNumbers(line); // Split line into individual strings

    // Perform a transform for storing string chunks as integers in line of matrix
    std::transform(std::istream_iterator<std::string>(stringOfNumbers),
    std::istream_iterator<std::string>(),
    std::back_inserter(matrixLine),
    [](const std::string& stringOfNumber)
    {
    return std::stoi(stringOfNumber);
    });
    }

    return result;
    }

    int main(int argc, char** argv)
    {
    std::vector<std::vector<int32_t>> result = readData("input.txt");

    // Writing the output into stdout
    for(auto line : result)
    {
    for(auto elem : line)
    {
    std::cout << elem << ", ";
    }
    std::cout << std::endl;
    }

    return 0;
    }

    Természetesen nem teszteltem teljes körűen, csak egyetlen bemenetre, de arra működött. :P

    input.txt:
    5 7
    2 3 4 -4 3 1 0
    -3 2 1023 3 -32 8 9
    -2 1 0 22 3 4 93
    5 3 8 2 -9 3 -9321
    2 3 4 -4 3 1 0

  • kispx

    addikt

    válasz #74220800 #3893 üzenetére

    0) fájl megnyitás után lekell ellenőrizni, hogy sikeresen megnyitotta-e a fájlt. Ha nem sikerült megnyitni a fájlt a program akkor is tovább fog menni. Ezt meg kell akadályozni.

    if (!myfile) {
    cerr << "Hiba: ...";
    return 0;
    }

    1)
    int x[n][ m ];

    N = 1000 és M = 1000 esetén ennek a mérete: 1000*1000*sizeof(int) lesz. Valószínűleg a 4 byte az int mérete nálad. Így több mint 3,8 MB ennek a változónak a mérete. Túl nagy, nem fér bele a stackbe. Olvasnivaló. Helyezd át a heapre:

    int n;
    int m;

    row>>n;
    row>>m;

    int **x = new int*[n];
    for(int i = 0; i< n ; i++){
    x[i] = new int[m];
    }

    Majd ha már nem használod a tömböt a delete[] x; utasítással töröld.

Új hozzászólás Aktív témák