c++ - C++ stdlib map::at 函数不像我期望的那样工作 struct key
问题描述
我正在为我的算法课编写作业。我有一个结构
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) 函数返回键的关联数据,但是当我在这里传递一个结构与键完全相同的数据时,它会抛出一个超出范围而不是返回与钥匙。我不能只传递一个与键完全相同数据的结构吗?它似乎没有检测为相同的键值。
解决方案
问题不在于 map.at() 函数的工作方式,而是我的结构中的小于运算符声明不正确。它比较了来自两个节点的不同值,而不是相同的值。这个网站帮助我意识到。 https://www.techiedelight.com/use-custom-objects-keys-std-map-cpp/
推荐阅读
- java - fileInputStream.available() 可以代替什么?
- angular - PrimeNG Panelmenu 菜单项和子菜单项的活动状态?
- php - 自动填充
- angular - 如何使用 Angular 材料步进器动态加载步骤
- react-native - 如何在 React Native 中获取音量级别信息
- apache-spark - 用于多重连接的 Spark SQL 广播
- sas - SAS:如何在包含最多案例的库中找到数据集?
- python-3.x - 导入 snowboydetect 生成错误
- java - 数独:某个位置的有效值
- android - Spinner Array 需要将其项目链接到现有布局?