ageoff
ageoff

Reputation: 2828

C++: Large multidimensional vector causes seg fault

I have a large file (50x11k) of a grid of numbers. All i am trying to do is place the values into a vector so that i can access the values of different lines at the same time. I get a seg fault everytime (i cannot even do a cout before a the while loop). Anyone see the issue?

If there is an easier way to do this then please let me know. Its a large file and I need to be able to compare the values of one row with another so a simple getline does not work, Is there a way to jump around a file and not "grab" the lines, but just "examine" the lines so that I can later go back an examine that same line by putting in that number? Like looking at the file like a big array? I wanna look at the third line and 5 character in that line at the same time i look at the 56th line and 9th character, something like that.

#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

//int g_Max = 0;

int main() {

    vector<vector<string> > grid;

    ifstream in("grid.txt");
    int row = 0;
    int column = 0;
    string c;

    if (!in) {
        cout << "NO!";
    }

    while (!in.eof()) {
        c = in.get();
        if ( c.compare("\n") == 0) {
            row++;
            column = 0;
        }
        else {
            c = grid[column][row];
            cout << grid[column][row];
            column++;
        }
    }

    return 0;
}

Upvotes: 0

Views: 392

Answers (2)

BigBoss
BigBoss

Reputation: 6914

If all you need is to access all lines at once why you don't declare it as std::vector<std::string> and each line is an string??

std::string s;
std::vector<std::string> lines;
while( std::getline(in, s) ) lines.push_back( s );
std::cout << "File contain " << lines.size() << " line" << std::endl;
std::cout << "Char at [1][2] is " << lines[1][2] << std::endl; // assume [1][2] is valid!

Upvotes: 0

Jonathan Wakely
Jonathan Wakely

Reputation: 171303

    vector<vector<string> > grid;

This declares an empty vector, with no elements.

        c = grid[column][row];

This accesses elements of the vector, but there are no elements.

If you change it to use vector::at() instead of vector::operator[] like so:

        c = grid.at(column).at(row);

then you'll get exceptions telling you you're accessing out of range.

You need to populate the vector with elements before you can access them. One way is to declare it with the right number of elements up front:

    vector<vector<string> > grid(11000, std::vector<string>(50));

You probably also want to fix your IO loop, testing !in.eof() is usually wrong. Why not read a line at a time and split the line up, instead of reading single characters?

while (getline(in, c))

Upvotes: 2

Related Questions