[英]Erasing elements of Deque container
我想刪除雙端隊列的元素。 當您有一個包含結構的雙端隊列並且想要從頭到尾打印元素時,卻又不想打印具有相同結構元素的元素,該怎么做?
我有一個這樣的結構:
struct New_Array {
array<array<int,4>,4> mytable;
int h;
};
雙端隊列充滿了先前過程中的元素。 您要打印雙端隊列中的所有元素,但是要打印的每個表必須具有唯一的“ h” 。 只有找到的帶有特定“ h”的第一個表必須被打印,具有“ h”的其他表則不應被打印。 我認為這也可以通過“查找”功能來補充。
我們從雙端隊列的后部開始發現的“ h”值將為0,並且將向雙端隊列的前部增加其值。
我已經試過了:
void Find_Solution_Path(deque<New_Array> Mydeque)
{
while(Mydeque.size()>0)
{
New_Array y=Mydeque.back();
PrintBoard(y); //this is a function that prints the 4x4 array.
Mydeque.pop_back();
for(unsigned int i=0; i<Mydeque.size(); i++)
{
New_Array xxx=Mydeque[i];
if(xxx.h==y.h)
{
Mydeque.erase(Mydeque[i]);
}
}
}
}
我不會使用雙端隊列,而是使用一組。 如果您絕對需要雙端隊列,那么請創建一個集。 用適當的准則定義<運算符<反映唯一性。 您將每個打印的元素插入到集中。 在打印之前,請檢查元素是否已存在於集合中(找到)。
HTH,馬丁
一種方法是使用std :: unique_copy 。
#include <iostream>
#include <algorithm>
#include <iterator>
#include <deque>
struct New_Array {
array<array<int,4>,4> mytable;
int h;
// unique_copy needs this:
bool operator==(const New_Array& other) { return h == other.h; }
};
ostream& operator<<(ostream& out, const New_Array& v)
{
return out << v.h;
}
int main()
{
std::deque<New_Array> q;
New_Array temp;
// {1, 1, 2, 2, 3, 3}
temp.h = 1;
q.push_back(temp);
q.push_back(temp);
temp.h = 2;
q.push_back(temp);
q.push_back(temp);
temp.h = 3;
q.push_back(temp);
q.push_back(temp);
unique_copy(q.begin(), q.end(), ostream_iterator<New_Array>(cout, "\n"));
}
需要對范圍進行排序 ,以使unique_copy
正常工作。 在上述情況下,無需排序,因為我們按順序插入了元素。
我相信@Martin的答案可能是最好的解決方案。 如果您無法更改返回deque
的函數的簽名,則可以從中構造一個set
,所有重復項將自動消失:
// First you need to declare a compare function for NewArray objects
struct NewArrayComp {
bool operator()(const NewArray& a1, const NewArray& a2) const {
return a1.h < a2.h;
}
};
// Then you can construct a set from the deque
deque<NewArray> dq;
// ...
std::set<NewArray, NewArrayComp> s(dq.begin(), dq.end());
// Finally you can just print the arrays (without duplicates)
for (const auto& a : s)
PrintBoard(a);
此解決方案的復雜度為O(n log n),而您的代碼為O(n ^ 2)。
此外,如果你不想重復支付從要素成本deque
進set
,你可以使用C ++ 11移動語義:
std::set<NewArray, NewArrayComp> s;
std::move(dq.begin(), dq.end(), std::inserter(s, s.begin()));
這只會移動所有元素,而不會復制它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.