想要使用 STL 扫描 C++ 中的二维数组

Want to scanf a 2-d array in c++ using STL

本文关键字:C++ 二维数组 扫描 STL      更新时间:2023-10-16

我想用 c++ stl 扫描二维数组。这就是我的做法,请告诉我它有什么问题。

int test;
scanf("%dn",&test);
VVI all_integers;
while(test--)
{
  all_integers.push_back(VI(istream_iterator<int>(cin),istream_iterator<int>()));
}

示例输入:-

4
1 2 3 4 5
1 2 3 4
1 2
1

其中测试是后面的行数。

你混合了std::cinscanf输入,这是故意的吗?只是std::cin >> test;有什么问题?

无论如何,程序的问题在于您一直读取到istream_iterator<int>(),这是"输入结束"。你正在尝试这样做 4 次。显然,输入只有一端。相反,您应该阅读到一行的末尾。

这是我的解决方案:

#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main(){
  int k;
  cin >> k; cout << endl << "k = " << k << endl;
  ostream_iterator<int> oi(cout, " ");
  vector<vector<int> > vpi;
  while(k--)
  {
    vpi.push_back(vector<int>(istream_iterator<int>(cin), istream_iterator<int>()));
    cin.clear();
    cout<<"k = "<< k <<endl;
    copy(vpi[vpi.size()-1].begin(), vpi[vpi.size()-1].end(), oi);
    cout<<endl;
  }
}

您需要在每个向量之后使用 ,<在 Linux=" 上按=" Ctrl=">+ 以使其工作。(+ 在 Linux 中是 eof。要使其单独使用 ,因为它是可取的,您需要使用 getline() 在字符串缓冲区中读取,然后从缓冲区读取。