C++ stdlib map::at 函数无法像我对结构键的预期那样工作

C++ stdlib map::at function not working like I expect for struct key

我正在为我的算法编写作业 class。我有一个结构

struct Node
{
    int firstPosition;
    int secondPosition;
    string firstColor;
    string secondColor;

    bool operator<(const Node& n) const {
        return (firstPosition < n.secondPosition);
    }

    bool operator==(const Node& n) const {
        return (firstPosition == n.firstPosition && secondPosition == n.secondPosition && firstColor == n.firstColor && secondColor == n.secondColor);
    }
};

我有一张名为“graph”的 stl 地图

map<Node, vector<Node>> graph;

我放置一个节点开始构建图

Node startNode = {1, 1, "R", "B"};
vector<Node> emptyVector;
graph.emplace(startNode, emptyVector);

我基本上是在尝试构建节点图,所以对于我得到的每一行输入(class 给了我一个输入文件 - sourceNode 和 targetNode 是我读入的整数,pathColor 是一个字符串我读入),我需要访问每个节点并根据我读入的内容将其他节点添加到它们的邻接列表中,因此在每一行的 while 循环中:

 for (auto& currentNode : graph) {
            // Case: sourceNode is the first position, so we make a new node with the updated first position
            if (currentNode.first.firstPosition == sourceNode ) {
                if (currentNode.first.secondColor == pathColor) {
                    Node newNode = {targetNode, currentNode.first.secondPosition, vertexColors[targetNode - 1], currentNode.first.secondColor};
                    graph.at(currentNode.first).emplace_back(newNode);  // Put the newly created node in the current node's adjacency list
                    vector<Node> emptierVector;
                    graph.emplace(newNode, emptierVector);              // Insert the newly created node into the graph
                }
            }
// More extra code down below

但是graph.at(currentNode.first).emplace_back(newNode);行抛出“在抛出 'std::out_of_range' 的实例后调用终止 what(): map::at" 即使我已经实现了 == 运算符重载并验证它有效并且我的数据匹配。我似乎无法从文档中找到我对该函数的误解在哪里。请帮助!

我希望 map.at(key) 函数能够 return 键的关联数据,但是当我在这里向它传递一个与键具有完全相同数据的结构时,它会抛出超出范围而不是 returning 与键关联的值。我不能只传递一个数据与键完全相同的结构吗?它似乎没有检测到相同的键值。

问题不在于 map.at() 函数的工作方式,而是我的结构中的小于运算符声明不正确。它比较来自两个节点的不同值而不是相同的值。 这个网站帮助我意识到。 https://www.techiedelight.com/use-custom-objects-keys-std-map-cpp/