2

我的问题是如何将二维向量写入文本文件。

我已经关注了这里的主题,这是我的代码根据我的需要进行了一些更改:

ofstream output_file("example.txt");
ostream_iterator<int> output_iterator(output_file, "\t");
for ( int i = 0 ; i < temp2d.size() ; i++ ) 
copy(temp2d.at(i).begin(), temp2d.at(i).end(), output_iterator);

我的问题是如何将向量逐行写入文件?

这就是我要的:

22 33 44
66 77 88
88 44 22

等等。

此代码将向量的所有元素写入同一行。

谢谢。

4

3 回答 3

1

我有 C++11,你可以这样做:

std::vector<std::vector<int> > v;

//do with v;

for(const auto& vt : v) {
     std::copy(vt.cbegin(), vt.cend(),
           std::ostream_iterator<int>(std::cout, " "));
     std::cout << '\n';
}

其他明智的类型定义是你的朋友。

typedef std::vector<int> int_v;
typedef std::vector<int_v> int_mat;
int_mat v;

for(int_mat::const_iterator it=v.begin(); it!=v.end(); ++it) {
     std::copy(vt->begin(), vt->end(),
           std::ostream_iterator<int>(std::cout, " "));
     std::cout << '\n';
}
于 2012-07-23T10:38:27.357 回答
1

这是一种方式:

#include <vector>
#include <iostream>

int main(){
  std::vector<std::vector<int> > vec;

  /* fill the vector ... */

  for(const auto& row : vec) {
    std::copy(row.cbegin(), row.cend(), std::ostream_iterator<int>(std::cout, " "));
  std::cout << '\n';
  }

  return 0;
}

用 编译gcc --std=c++0x test_vector.cc

于 2012-07-23T10:42:33.840 回答
1

复制行后打印出一个换行符,即在 for 循环结束时:

for(...)
{
  : // other code
  output_file << '\n';
}
于 2012-07-23T10:29:59.290 回答