C++ 比较两个不同列表的内容
我试图比较两个不同列表的内容。我使用迭代器循环遍历列表。我正在检查列表1中的最后一个元素是否出现在列表2中。下面是一段代码C++ 比较两个不同列表的内容,c++,list,iterator,containers,C++,List,Iterator,Containers,我试图比较两个不同列表的内容。我使用迭代器循环遍历列表。我正在检查列表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 */
/* 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;
}
}
以下是此行的错误:
error: no match for 'operator*' (operand type is '__gnu_cxx::__alloc_traits<std::allocator<edgeLineShape> >::value_type {aka edgeLineShape}')
错误:与“operator*”不匹配(操作数类型为“\uu gnu\u cxx::\uu alloc\u traits::value\u type{aka edgeLineShape}”)
我目前对迭代器的*运算符的理解是,它将取消对迭代器的引用,就像使用*运算符取消对指针的引用一样
这不正确吗?正如Semyon所提到的,它是一个参考,因此不能简单地使用derefence操作符 但是,您可以这样做:
*(pathContour.end()--)
如果您仍然坚持使用迭代器。因为
返回的是引用,而不是迭代器(请注意错误内容:(操作数类型为'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++)
或者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 */ }
#包括
auto it=std::find(p_lineList->begin(),p_lineList->end(),pathCountour.back());
如果(it!=p_lineList->end()){/*找到元素*/}
但可能您应该考虑其他可以避免线性搜索的容器。
<代码>:ST:::vector::()/代码>不返回迭代器。它返回对最后一个元素的引用,因此无需使用运算符*
对其进行解引用,此外:*(pathcourto.back()
如果pathContour
为空,则会导致未定义的行为。嗯,我很喜欢这个想法,它肯定会起作用,但有人能建议另一种方法来做同样的事情吗?这是最好的做法吗?在这种情况下使用它会更好。如果pathCountour为空呢?@ROX感谢您指出这一点。在这个例子中,我们将我假设它不是空的,但我会确保进行检查,以确保在冷凝建议为空+1时不会发生这种情况。我实际上使用的是C++11。自动使用从未像您刚才那样向我明确说明过,谢谢您!按回答标记,因为这是我所走的路线!
for (auto lineIterator : p_lineList)
#include <algorithm>
auto it = std::find(p_lineList->begin(), p_lineList->end(), , pathCountour.back());
if (it != p_lineList->end()) { /* element found */ }