Domanda

I declare a struct called Position with 2 data members: x, y. I want to store instances of these structs into a std::set. How can I later retrieve the value of x, y from the right Position struct?

struct Position
{
    long m_x;
    long m_y;
    Position(long x, long y) : m_x(x), m_y(y) {}
}

std::set<Position> m_visited;

What I'm trying to implement is a tracking system for an entity in a 2D map. Every time the entity moves, its current position will be recorded into the set, so that later I can find out where it has been to.

I record its current position by calling this every time it moves.

m_visited.insert(Position(CorX(),CorY());

And later, I'd like to see if the new cell which my entity is going to has been visited or not. If it is, then I'd tell the entity to pick other cells to do something by saying something like

for (set<Position>:iterator i = m_visited.begin(); i != m_visited.end(); i++)
{
    if ([X cor of next cell] != [X cor of a visited cell] && [Y cor of next cell] != [Y cor of a visited cell])
    {
         do something
    }
}

Problem is I don't know how to find the right cell which has the right data to compare to. Sorry if this sounds really confusing

È stato utile?

Soluzione

Iterator i can be used like a pointer to Position, so you can write

Position visited = ...
for (set<Position>:iterator i = m_visited.begin(); i != m_visited.end(); i++) {
    if (i->m_x == visited.m_x && i->m_y == visited.m_y) {
        ... // Been there before
    }
}

However, this use of the set is not much different from a use of a list, because the serach is linear. You can find out if the item you have inserted is a new one without a loop by checking the return value of insert:

if (!m_visited.insert(Position(CorX(),CorY())).second) {
    // Position at { CorX(), CorY() } has been visited
}

set::insert returns a pair with the second member set to true if the item that you have inserted is a new one, and to false if another item with the same data is already in the set.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top