[英]Comparing the contents of two different lists
我試圖比較兩個不同列表的內容。 我正在使用迭代器遍歷列表。 我正在檢查列表1中的最后一個元素是否出現在列表2中。這是代碼的片段
/* This section will loop through the list to make sure that the line segment that was added to the
* contour path is updated to be visited
*/
for(plf::colony<edgeLineShape>::iterator lineIterator = p_lineList->begin(); lineIterator != p_lineList->end(); lineIterator++)
{
edgeLineShape temp = *lineIterator;
if(temp == *(pathContour.back()))
{
lineSet = true;
lineIterator->setVisitedStatus(true);
break;
}
}
pathContour定義為std::vector<edgeLineShape> pathContour
。 這是棘手的部分,我在兩個不同的容器之間進行比較。 實際上有兩種不同的數據結構。 值得慶幸的是,plf :: colony數據類型滿足了C ++容器的要求,而不滿足要求。
當我去編譯時,我在線上給出了一個錯誤:
if(temp == *(pathContour.back())
這是這一行的錯誤:
error: no match for 'operator*' (operand type is '__gnu_cxx::__alloc_traits<std::allocator<edgeLineShape> >::value_type {aka edgeLineShape}')
我目前對迭代器的*運算符的理解是,它將取消引用迭代器,就像使用*運算符取消引用指針一樣?
這不正確嗎?
正如Semyon所提到的,它是一個參考,所以你不能簡單地使用derefence運算符。
但是,你可以這樣做:
*(pathContour.end()--)
如果你堅持使用迭代器。
因為back
返回引用,而不是迭代器(注意錯誤內容:( (operand type is 'blablabla {aka edgeLineShape}')
)。 您可以像平常一樣比較它:
if (temp == pathContour.back())
但實際上, temp
是沒有必要的,因為你只是在這里使用它,所以你可以做到
if (*lineIterator == pathContour.back())
另外,如果您使用的是C ++ 11或更高版本,則應該查看auto
,這可以轉為:
for(plf::colony<edgeLineShape>::iterator lineIterator = p_lineList->begin(); lineIterator != p_lineList->end(); lineIterator++)
進入這個:
for (auto lineIterator = p_lineList->begin(); lineIterator != p_lineList->end(); lineIterator++)
或foreach,它可以將其濃縮為更簡潔:
for (auto lineIterator : p_lineList)
您問題中的代碼不是比較容器。 也許這是一個XY問題?
與您的代碼等效的C ++ ic是:
#include <algorithm>
auto it = std::find(p_lineList->begin(), p_lineList->end(), , pathCountour.back());
if (it != p_lineList->end()) { /* element found */ }
但是可能你應該考慮一些其他可以避免線性搜索的容器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.