Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Flatten 2D Vector in C++
Suppose we have a 2D vector, we have to design and implement an iterator to flatten that 2d vector. There will be different methods as follows −
next() − This will return the next element of the current element
hasNext() − This will check whether next element is present or not
So, if the input is like [[1,2],[3],[4]] then if we call the functions as follows −
iterator.next();
iterator.next();
iterator.next();
iterator.hasNext();
iterator.hasNext();
iterator.next();
iterator.hasNext();
then the output will be [1,2,3,true, true,4,false]
To solve this, we will follow these steps −
Define one 2D array v
Define initializer this will take one 2D array v,
rowPointer := 0
colPointer := 0
n := size of v
-
while (rowPointer < n and colPointer >= size of v[rowPointer]), do −
(increase rowPointer by 1)
Define a function next()
x := v[rowPointer, colPointer]
(increase colPointer by 1)
-
if colPointer is same as size of v[rowPointer], then −
colPointer := 0
(increase rowPointer by 1)
-
while (rowPointer < n and colPointer >= size of v[rowPointer]), do −
(increase rowPointer by 1)
return x
Define a function hasNext()
return false when rowPointer is same as n
Example
Let us see the following implementation to get better understanding −
#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());
}
Input
ob.next() ob.next() ob.next() ob.hasNext() ob.next() ob.hasNext()
Output
1 2 3 1 4 0