比较两个不同列表的内容

Comparing the contents of two different lists

本文关键字:列表 两个 比较      更新时间:2023-10-16

我正在尝试比较两个不同列表的内容。我正在使用迭代器循环浏览列表。我正在检查列表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。这是一个棘手的部分,我正在比较两个不同的容器之间。实际上,两个不同的数据架构。值得庆幸的是,thoguh 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}')

我目前对 *迭代器 *操作员的理解是,它将像使用 *操作员使用指针一样放置迭代器吗?

这是不正确的吗?

因为 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)

正如Semyon所提到的,它是一个参考,因此您不能简单地使用DereFence Operator。

但是,您可以这样做:

*(pathContour.end()--)

如果您使用迭代器。

问题中的代码没有比较容器。也许这是一个XY问题?

等同于您的代码的C IC是:

#include <algorithm>
auto it = std::find(p_lineList->begin(), p_lineList->end(), , pathCountour.back());
if (it != p_lineList->end()) { /* element found */ } 

,但您可能应该考虑一些可以避免线性搜索的容器。