1

SquareGrid.h

#pragma once

#ifndef SQUARE_GRID_H
#define  SQUARE_GRID_H

#include <set>
#include <array>
#include <vector>
#include <unordered_map>
#include <queue>

struct SPODGridPosition
{
    int x;
    int y;
};

bool operator < (const SPODGridPosition & x1, const SPODGridPosition & x2);

bool operator == (const SPODGridPosition & x1, const SPODGridPosition & x2);

bool operator != (const SPODGridPosition & x1, const SPODGridPosition & x2);

struct SSquareGrid
{
    typedef  SPODGridPosition Location;
    static std::array<Location, 4> m_dirs;
    std::set<Location> m_wallsSet;

    SSquareGrid(int width, int height)
        : m_width(width)
        , m_height(height)
    {

    }
    void AddOrDeleteWall(int x, int y)
    {
        Location next{ x,y };
        auto iter = m_wallsSet.find(next);
        if ( iter != m_wallsSet.end())
        {
            m_wallsSet.erase(iter);
        }
        m_wallsSet.insert(next);
    }
    bool InBounds(const Location & id) const
    {
        return 0 < id.x && id.x < m_width && 0 < id.y && id.y < m_height;
    }
    bool Passable(const Location & id) const
    {
        return m_wallsSet.find(id) != m_wallsSet.end();
    }
    std::vector<Location> Neighbors(Location id) const
    {
        std::vector<Location> result;
        for (auto const dir : m_dirs)
        {
            Location next{ id.x + dir.x, id.y + dir.y };
            if (InBounds(next) && Passable(next))
            {
                result.push_back(next);
            }
        }
        return result;
    }
    int m_width;
    int m_height;
};

extern SSquareGrid g_SquareGrid;

#endif // !SQUARE_GRID_H

SquarGrid.cpp

#include "SquareGrid.h"

SSquareGrid g_SSquareGrid(30, 30);

bool operator < (const SPODGridPosition & x1, const SPODGridPosition & x2)
{
    return std::tie(x1.x, x1.y) < std::tie(x2.x, x2.y);
}

bool operator == (const SPODGridPosition & x1, const SPODGridPosition & x2)
{
    return x1.x == x2.x && x1.y == x2.y;
}

bool operator != (const SPODGridPosition & x1, const SPODGridPosition & x2)
{
    return !(x1 == x2);
}

FindPath.h

#pragma once

#include "SquareGrid.h"

template <typename Graph, typename Location>
std::unordered_map<Location, Location> BreadthFirstSearch(const Graph & graph, Location start, Location goal);

void FindPath(int n32SelfX, int n32SelfY, int n32TargetX, int n32TargetY);

FindPath.cpp

#include "FindPath.h"

std::array<SPODGridPosition, 4> SSquareGrid::m_dirs = { SPODGridPosition{0,1},
SPODGridPosition{1,0}, SPODGridPosition{0,-1}, SPODGridPosition{-1,0} };

template <typename Graph, typename Location>
std::unordered_map<Location, Location>  BreadthFirstSearch(const Graph & graph, Location start, Location goal)
{
    std::queue<Location> frontier;
    frontier.push(start);
    std::unordered_map<Location, Location> came_from;
    came_from[start] = start;
    while (!frontier.empty())
    {
        auto current = frontier.front();
        frontier.pop();
        if (current == goal) break;
        for (auto & next : graph.Neighbors(current))
        {
            frontier.push(next);
            came_from[next] = current;
        }
    }
    return came_from;
}

void FindPath(int n32SelfX, int n32SelfY, int n32TargetX, int n32TargetY)
{
    auto came_from = BreadthFirstSearch(g_SquareGrid, SPODGridPosition{ n32SelfX, n32SelfY },
        SPODGridPosition{ n32TargetX, n32TargetY });
}

Ошибка : C2280 "std::hash<_Kty>::hash(const std::hash<_Kty> &)": предпринята попытка ссылки на удаленную функцию MyGame c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.13.26128\include\unordered_map 132

Замечание : Если содержимое FindPath удалить, то компилируется.

14
  • А на какую строку ругается-то?
    – VladD
    12 мар 2018 в 21:52
  • Не, на какую строку в вашем коде ругается компилятор? Дайте полное сообщение об ошибке.
    – VladD
    12 мар 2018 в 21:54
  • Ошибка C2280 "std::hash<_Kty>::hash(const std::hash<_Kty> &)": предпринята попытка ссылки на удаленную функцию MyGame c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.13.26128\include\unordered_map 132
    – Tarakan
    12 мар 2018 в 21:56
  • 1
    1) Ещё полнее, пожалуйста. Там должен быть контекст ошибки. 2) И лучше класть это не в комментарий, а в вопрос (там есть ссылка «править»).
    – VladD
    12 мар 2018 в 21:57
  • 1) Это все информация. Больше VC 17 мне ничего не выдает. 2) Я же в конце вопроса разместил.
    – Tarakan
    12 мар 2018 в 22:01

1 ответ 1

4

Вы не определили hasher для своего SPODGridPosition. В результате компилятор подхватывает какую-то свою специализацию std::hash<SPODGridPosition> для стандартного std::hash<>. А в ней удален конструктор копирования, что и приводит к ошибке где-то в недрах конструкции unordered_map.

Это в любом случае не могло работать, ибо как надо хэшить ваш SPODGridPosition компилятор не знает. Определите hasher для SPODGridPosition и укажите его в качестве третьего параметра шаблона unordered_map.

4
  • это скорее всего так и есть 12 мар 2018 в 23:26
  • равенство у него определено 12 мар 2018 в 23:32
  • @AR Hovsepyan: А, точно, спасибо. Не заметил сразу. 13 мар 2018 в 0:05
  • @ Qwertiy, да, не ответ, но улучшить код тоже полезно 13 мар 2018 в 14:21

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.