比较两个不同列表的内容

时间:2017-09-27 00:28:52

标签: 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
             */ 
            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}')

我目前对迭代器的*运算符的理解是,它将取消引用迭代器,就像使用*运算符取消引用指针一样?

这不正确吗?

3 个答案:

答案 0 :(得分:1)

正如Semyon所提到的,它是一个参考,所以你不能简单地使用derefence运算符。

但是,你可以这样做:

*(pathContour.end()--)

如果你坚持使用迭代器。

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

与您的代码等效的C ++ ic是:

#include <algorithm>

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

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

相关问题