【问题标题】:C++ stdlib map::at function not working like I expect for struct keyC++ stdlib map::at 函数不像我期望的那样工作 struct key
【发布时间】:2020-12-15 18:56:48
【问题描述】:

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

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

我实际上是在尝试构建节点图,因此对于我得到的每一行输入(类给了我一个输入文件 - 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) 函数返回键的关联数据,但是当我在这里传递一个与键完全相同的数据的结构时,它会抛出一个超出范围而不是返回与键关联的值。我不能只传递一个与键完全相同数据的结构吗?它似乎没有检测为相同的键值。

【问题讨论】:

  • 例外是因为graph.at(currentNode.first) 没有向graph 添加新元素(这是一件好事,因为添加新元素会破坏范围-for)。也就是说,因为currentNode 来自graph,所以有些东西已经坏了。我,我怀疑graph.emplace(newNode, emptierVector); 可能是坏孩子,在容器被for 迭代时添加到容器中。您可以插入 map 而不会损坏迭代器,但我不确定它对地图的末端有什么作用。
  • 我认为这里有一个很好的问题,但我们需要更多信息,minimal reproducible example 会很好,以帮助找出答案。

标签: c++ stl maps


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多