title: Writing multidimensional to CSV file
body: <p>I have a rather large two-dimensional vector of strings I'd like to write to a CSV file but my code crashes when I write. Any suggestions?</p>
  
  <pre><code>if (outfile.is_open()) {
      for (int i = 0; i &lt; width.size() - 1; i++) {
          for (int j = 0; j &lt; rows.size() - 1; j++) {
              outfile &lt;&lt; cells[i][j] &lt;&lt; ",";
          }
          outfile &lt;&lt; endl;
      }
  } else cout &lt;&lt; "Unable to write.";
  </code></pre>
  
  <p>Declaration of width, rows and cell:</p>
  
  <pre><code>//Declare stuff
  vector&lt;string&gt; rows, cols, width;
  vector&lt; vector&lt;string&gt; &gt; cells;
  string line;
  
  //Open input file
  std::ifstream infile("99-110.csv", ios_base::in);
  std::ofstream outfile("99-110_corr.csv", ios_base::out);
  
  
  //Create vector with each row as an index
  while (getline(infile, line)) {
      rows.push_back(line);
      width = split(rows[0], ",");
  }
  
  //Split each vector index into a 2D vector
  for (int i = 0; i &lt; rows.size(); i++) {
      cols = split(rows[i], ",");
      cells.push_back(cols);
  }
  </code></pre>
  
  <p>As it turns out I had rows.size() and width.size() mixed up. I swapped them and now everything seems to work for small files, but for files larger than around 500 MB my script crashes with <em>terminate called after throwing an instance of 'std::bad_alloc'</em>. It seems to be crashing during the for loop where I split each vector index into a 2D vector (last for loop provided above). The maximum size for the vector "cells" is 357,913,941 but I've calculated the actual size of the vector to be 97,780,085.</p>