代码之家  ›  专栏  ›  技术社区  ›  philm

比较两个不同列表的内容

  •  1
  • philm  · 技术社区  · 8 年前

    我试图比较两个不同列表的内容。我使用迭代器循环遍历列表。我正在检查列表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;
                    }
    }
    

    路径轮廓定义为 std::vector<edgeLineShape> pathContour

    当我去编译时,我在第行给出了一个错误:

    if(temp == *(pathContour.back())
    

    这是此行的错误:

    error: no match for 'operator*' (operand type is '__gnu_cxx::__alloc_traits<std::allocator<edgeLineShape> >::value_type {aka edgeLineShape}')
    

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

    3 回复  |  直到 8 年前
        1
  •  1
  •   Tasgall    8 年前

    因为 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
  •   codingDude    8 年前

    但是,你可以这样做:

    *(pathContour.end()--)
    

    如果你坚持使用迭代器。

        3
  •  1
  •   o11c    8 年前

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

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

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

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