Writing huge 2D vectors to text file too slow I have 10 large (34 million cell) 2D gridded vectors storing doubles. When written they are over 200 MB in size. I use an ofstream object to write them to a text file (.csv format), one element at a time, using two for loops (one for my rows, one for my columns). They take way to long to write. Is there a faster way to write from these vectors?

(I am using Visual Studio 2012.)

// Resizing of vectors
flowDirGrid.resize(rows, std::vector&lt;double&gt;(cols, NODATA));

// Do some processing
....

// Outputting processed data
ofstream outfile3("FlowDir.dat");
if(!outfile3.good())
    return;

for(int i=0; i&lt;rows; i++)        
    {
        for (int j=0; j&lt;cols; j++)
        {
            if(elevation[i][j]!=NODATA)
                outfile3 &lt;&lt; flowDirGrid[i][j]&lt;&lt;" ";
            else
                outfile3 &lt;&lt; NODATA&lt;&lt;" ";
        }
        outfile3 &lt;&lt; std::endl;
    }

outfile3.close();
The output-writing code should reside in a function that takes two parameters: the flowDirGrid and a filename.

Don't omit braces on multi-line conditionals.  It's a filthy habit, and someday you will contribute to a coding accident like this.

A performance problem is outputting std::endl at the end of every line, which causes a flush.  Output '\n' instead.