【问题标题】:C++ Iterating through a list to compare positionsC ++迭代列表以比较位置
【发布时间】:2018-10-19 01:24:00
【问题描述】:

我有一个名为 m_positions 的 Vector2f 位置列表,我正在尝试将第一个位置与除自身之外的所有其他位置进行比较。

目前我两次获得了前面的位置(startPositionotherPositions),以便稍后进行比较。

然后它遍历列表并尝试使用 Advance 或 next 将 otherPositions 获取到第二组,但两者都会导致错误,所以我不太确定如何执行此操作。

最后它比较startPositionotherPositions的x和y值来检查它们是否相同。

    auto startPosition = m_positions.front();
    auto otherPositions = m_positions.front();

    for(auto it = m_positions.begin(); it != m_positions.end(); ++it)
    {
        //advance (otherPositions, 1);
        //next (otherPositions, 1);

        if(otherPositions != m_positions.back())
        {
            if(startPosition == otherPositions)
            {
                return 1;
            }
        }
    }

提前错误:

错误:'struct std::iterator_traits >'中没有​​名为'difference_type'的类型|

错误:没有匹配函数调用'__iterator_category(sf::Vector2&)'|

错误:'struct std::iterator_traits >'中没有​​名为'iterator_category'的类型|

下一个错误:

错误:没有匹配函数调用'next(sf::Vector2&, int)'|

错误:'struct std::iterator_traits >'中没有​​名为'difference_type'的类型|

【问题讨论】:

  • front() 返回对项目的引用,而不是迭代器。你得到的确切错误是什么?如果这是我认为的那样,您可以将示例缩短为一个非常简单的示例,而无需解释尝试比较值和编写循环。
  • @PaulMcKenzie 我在代码下方添加了错误,但不完全确定他们要求什么。
  • 您对什么是迭代器和什么是值的引用感到困惑。
  • 另外,std::find(m_positions.begin() + 1, m_positions.end(), m_positions.front()) 不会完成与您的循环相同的事情吗?

标签: c++ list iteration


【解决方案1】:

std::advance 函数需要一个迭代器作为第一个参数,而不是对值的引用。

这个:

auto otherPositions = m_positions.front();

返回对列表中第一项的引用,而不是第一项的迭代器。

如果您想获得第一项的迭代器,则可以执行以下操作:

auto otherPositions = m_positions.begin();

然后在循环中,如果要测试值,则取消引用迭代器并使用所需的值对其进行测试:

if(*otherPositions != m_positions.back())

但我敢打赌,您可以简单地执行此操作来完成原始代码尝试执行的相同操作:

#include <algorithm>
//...
auto start = m_positions.begin();
auto iter = std::find(std::next(start), m_positions.end(), 
                      m_positions.front());
if (iter != m_positions.end())
   return 1;

【讨论】:

    猜你喜欢
    • 2012-11-05
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多