Le Ginger One
Le Ginger One

Reputation: 3

C++ Iterating through a list to compare positions

I have a list of Vector2f positions called m_positions and I'm trying to compare the first position with all other positions except for itself.

At the moment I get the position for the front twice (startPosition and otherPositions) so they can be compared later on.

Then it's iterating through the list and was trying to use either advance or next to get otherPositions to the second set but both cause errors so I'm not quite sure how to do this.

Finally it compares the x and y values of startPosition and otherPositions to check if they are the same.

    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;
            }
        }
    }

Advance Error:

error: no type named 'difference_type' in 'struct std::iterator_traits >'|

error: no matching function for call to '__iterator_category(sf::Vector2&)'|

error: no type named 'iterator_category' in 'struct std::iterator_traits >'|

Next Error:

error: no matching function for call to 'next(sf::Vector2&, int)'|

error: no type named 'difference_type' in 'struct std::iterator_traits >'|

Upvotes: 0

Views: 251

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35455

The std::advance function requires an iterator as the first argument, not a reference to a value.

This:

auto otherPositions = m_positions.front();

returns a reference to the first item in the list, not an iterator to the first item.

If you want to get an iterator to the first item, then the following could be done:

auto otherPositions = m_positions.begin();

and then in the loop, if you want to test values, you dereference the iterator and test it with the desired value:

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

But I would wager that you could have just simply done this to accomplish the same thing your original code is attempting to do:

#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;

Upvotes: 1

Related Questions