假设我们有一个2D向量,我们必须设计和实现一个迭代器来平铺2D向量。会有以下不同的方法-
next()-这将返回当前元素的下一个元素
hasNext()-这将检查下一个元素是否存在
因此,如果输入类似于[[1,2 ,, [3],[4]],则我们按如下方式调用函数-
iterator.next();
iterator.next();
iterator.next();
iterator.hasNext();
iterator.hasNext();
iterator.next();
iterator.hasNext();
那么输出将是[1,2,3,true,true,4,false]
为了解决这个问题,我们将遵循以下步骤-
定义一个2D数组v
定义初始值设定项,它将采用一个2D数组v
rowPointer:= 0
colPointer:= 0
n:= v的大小
而(rowPointer <n和colPointer> = v [rowPointer]的大小),则执行-
(将rowPointer增加1)
定义功能 next()
x:= v [rowPointer,colPointer]
(使colPointer增加1)
如果colPointer与v [rowPointer]的大小相同,则-
(将rowPointer增加1)
colPointer:= 0
(将rowPointer增加1)
而(rowPointer <n和colPointer> = v [rowPointer]的大小),则执行-
返回x
定义功能 hasNext()
当rowPointer与n相同时返回false
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h> using namespace std; class Vector2D { public: int rowPointer, colPointer; int n; vector<vector<int< > v; Vector2D(vector<vector<int< >& v){ this->v = v; rowPointer = 0; colPointer = 0; n = v.size(); while (rowPointer < n && colPointer >= v[rowPointer].size()){ rowPointer++; } } int next(){ //cout << rowPointer << " " << colPointer << endl; int x = v[rowPointer][colPointer]; colPointer++; if (colPointer == v[rowPointer].size()) { colPointer = 0; rowPointer++; while (rowPointer < n && colPointer >= v[rowPointer].size()) { rowPointer++; } } return x; } bool hasNext(){ return !(rowPointer == n); } }; main(){ vector<vector<int<> v = {{1,2},{3},{4}}; Vector2D ob(v); cout << (ob.next()) << endl; cout << (ob.next()) << endl; cout << (ob.next()) << endl; cout << (ob.hasNext()) << endl; cout << (ob.next()) << endl; cout << (ob.hasNext()); }
ob.next() ob.next() ob.next() ob.hasNext() ob.next() ob.hasNext()
输出结果
1 2 3 1 4 0