C++ 中的交錯迭代器
假設有兩個一維陣列,我們需要實現一個可以交替返回其元素的迭代器。這裡將有兩種方法 −
next() − 獲取下一個元素
hasNext() − 檢查下一個元素是否存在。
因此,如果輸入類似 v1 = [1,2] v2 = [3,4,5,6],則輸出將是 [1,3,2,4,5,6]
為了解決這個問題,我們將按照以下步驟操作 −
定義一個對 q 的佇列
從初始化程式中獲取兩個陣列 v1 和 v2,
如果 v1 的大小,則 −
將 { 0, 0} 插入 q
如果 v2 的大小,則 −
將 { 0, 1} 插入 q
定義一個成對的臨時 temp
temp := q 的第一個元素
從 q 中刪除元素
ret := 0
如果 temp.second 與 1 相同,則 −
ret := v2[temp.first]
(將 temp.first 增加 1)
如果 temp.first < v2 的大小,則 −
將 temp 插入 q
否則
ret := v1[temp.first]
(將 temp.first 增加 1)
如果 temp.first < v1 的大小,則 −
將 temp 插入 q
返回 ret
定義一個函式 hasNext()
當 q 不為空時,返回 true
示例
讓我們看一下以下實現,以便更好地理解 −
#include <bits/stdc++.h>
using namespace std;
class ZigzagIterator {
public:
queue <pair<int, int>> q;
vector <int< v1, v2;
ZigzagIterator(vector<int<& v1, vector<int<& v2) {
this->v1 = v1;
this->v2 = v2;
if (v1.size()) {
q.push({ 0, 0 });
}
if (v2.size()) {
q.push({ 0, 1 });
}
}
int next() {
pair<int, int> temp;
temp = q.front();
q.pop();
int ret = 0;
if (temp.second == 1) {
ret = v2[temp.first];
temp.first++;
if (temp.first < v2.size())
q.push(temp);
}
else {
ret = v1[temp.first];
temp.first++;
if (temp.first < v1.size())
q.push(temp);
}
return ret;
}
bool hasNext() {
return !q.empty();
}
};
main(){
vector<int< v1 = {1,3,5,7}, v2 = {2,4,6,8,10,12,17};
ZigzagIterator ob(v1, v2);
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
}輸入
{1,3,5,7},{2,4,6,8,10,12,17}輸出
1 2 True 3 4 5 True 6 7 8 10 True 12 17 False
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP