c++ - 指向对象的指针映射上的迭代器作为键 c++

标签 c++ pointers iterator

我正在实现回溯算法来解决数独问题,但我在使用 map 时遇到了一些问题。 谁能告诉我为什么在编译我的代码时会出现这两个错误?第一个错误是关于在 map 上声明迭代器的行。第二个是在执行 Adj[&node] = mList;

错误:

错误 C2664 'std::_Tree_const_iterator>>> std::_Tree>::find(Node *const &) const':无法将参数 1 从 'const Node *' 转换为 'Node *const &'

错误 C2679“[”二进制:没有找到接受类型为“const Node *”的右操作数的运算符(或者没有可接受的转换)

(我的 Visual Studio 是法语的,所以我翻译了错误信息。希望这样没问题)

我的错误代码:

template<class T>
void AdjList<T>::addElement(const Node<T>& node, const vector<Node<T>>& vecOfNeighbours) {
    typename map< Node<T>*, LinkedList<T>>::iterator mit = Adj.find(&node);
    if (mit!=Adj.end()) {
        LinkedList<T> mList;
        for (typename vector<Node<T>>::const_iterator it = vecOfNeighbours.begin(); it != vecOfNeighbours.end(); it++) {
            mList.Add((*it).getValue()[0]);
        }
        Adj[&node] = mList;
    }
}

我的类(class)定义:

template<class T>
class AdjList
{
private:
    map<Node<T>*, LinkedList<T>> Adj;
public:
    AdjList();
    AdjList(const AdjList<T>& adjlist);
    AdjList(const Node<T>& node, const vector<Node<T>>& vecOfNeighbours);
    void addElement(const Node<T>& node, const vector<Node<T>>& vecOfNeighbours);
    void Print() const;
};

template<class T>
class LinkedList
{
    Node<T>* head;
    int  getEndList();
    Node<T>* returnFrontEnd(void) const;

public:
    LinkedList();
    LinkedList(T data);
    LinkedList(const LinkedList<T>& list);
    LinkedList<T>& operator=(const LinkedList<T>& list);
    void Add(T data);
    void AddAt(int index, T data);
    void Print();
    ~LinkedList();
};

template<class T>
class Node
{
protected:
    vector<T> _value;
    Node<T>*  child;

public:
    Node(T value);
    void addValue(T value);
    Node<T>* clone() const;
    Node(const Node<T>& node);
    vector<T> getValue() const;
    Node<T>* returnChild() const;
    void AddChild(const Node<T>& node); 
    Node& operator=(const Node<T>& node);
    ~Node();
};

最佳答案

你需要抛弃const。为什么?看一看:

void AdjList<T>::addElement(const Node<T>& node, const vector<Node<T>>&) 

好的,所以 node 是一个常量引用,

typename map< Node<T>*, LinkedList<T>>::iterator mit = Adj.find(&node);

但是这个迭代器会有一个非常量指针。因此,如果允许这样做,您将能够从 const 引用中获取非常量指针。这显然需要放弃 const(你不这样做)。

关于c++ - 指向对象的指针映射上的迭代器作为键 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33732247/

相关文章:

c++ - 在 vector 中的 vector 之间移动指针会导致 vector 迭代器不兼容

c - 在 C 中使用带指针的结构和数组

c++ - C++中的字符串指针

c++ - 自定义容器上的C++ “periodic”迭代器

c++ - 指向 std::string 中特定字符的迭代器

c++ - 为什么我不能递减 std::array::end()?

c++ - 函数返回在另一个类中定义的枚举(致命链接错误)

C++ 列表迭代器 reverse_iterator

c++ - 如何通过在OnEraseBkgnd()中使用StretchBlt制作缩小位图的动画并摆脱其周围的 “shadow”? (MFC)

c - MCU 上的 RTC - 函数指针和回调