Anonymous
Почему моя программа сообщает, что ячейка памяти находится за пределами неупорядоченной карты?
Сообщение
Anonymous » 08 май 2024, 21:43
В настоящее время я пишу консольную программу на C++, которая строит сеть/граф узлов и дуг, соединяющихся друг с другом с помощью неупорядоченных карт. Цель приложения — продемонстрировать «наиболее эффективный» способ обработки команд и получения информации из сети/графа. Я приложил [схему аналогичного примера].(
https://i.sstatic.net/51FY0RHO.png ).
Ниже приведена моя BuildNetwork() метод в моем файле Network.cpp, а также в моих классах Graph.cpp, Node.cpp и Arc.cpp, чтобы вы могли получить представление о том, как моя сеть построен:
Код: Выделить всё
bool Navigation::BuildNetwork(const std::string& fileNamePlaces, const std::string& fileNameLinks)
{
std::ifstream finPlaces(fileNamePlaces), finLinks(fileNameLinks);
if (!finPlaces || !finLinks)
return false;
std::string line;
// Parse Places
while (getline(finPlaces, line)) {
std::istringstream iss(line);
std::string name, idStr, latitudeStr, longitudeStr;
if (getline(iss, name, ',') && getline(iss, idStr, ',') && getline(iss, latitudeStr, ',') && getline(iss, longitudeStr)) {
int id = std::stoi(idStr);
double latitude = std::stod(latitudeStr), longitude = std::stod(longitudeStr);
Node node(id, name, latitude, longitude);
networkGraph.addNode(node);
}
}
// Parse Links
while (getline(finLinks, line)) {
std::istringstream iss(line);
std::string startIdStr, endIdStr, modeStr;
if (getline(iss, startIdStr, ',') && getline(iss, endIdStr, ',') && getline(iss, modeStr)) {
int startNodeId = std::stoi(startIdStr), endNodeId = std::stoi(endIdStr);
TransportMode mode = parseTransportMode(modeStr);
Arc arc(startNodeId, endNodeId, mode);
networkGraph.addArc(startNodeId, arc);
}
}
return true;
}
// Helper function to parse string to TransportMode
TransportMode Navigation::parseTransportMode(const std::string& modeStr) {
static const std::unordered_map modeMap = {
{"Ship", TransportMode::Ship}, {"Rail", TransportMode::Rail},
{"Bus", TransportMode::Bus}, {"Car", TransportMode::Car},
{"Bike", TransportMode::Bike}, {"Foot", TransportMode::Foot}
};
auto it = modeMap.find(modeStr);
if (it != modeMap.end())
return it->second;
return TransportMode::Foot; // Default or error case
}
Код: Выделить всё
#include "Graph.h"
Graph::Graph() {}
Graph::~Graph() {}
void Graph::addNode(const Node& node) {
nodes[node.getId()] = node;
}
void Graph::addArc(int startNodeID, const Arc& arc) {
if (nodeExists(startNodeID) && nodeExists(arc.getEndNodeID())) {
if (adjacencyList.find(startNodeID) == adjacencyList.end()) {
adjacencyList[startNodeID] = std::vector(); // Initialize if not already
}
adjacencyList[startNodeID].push_back(arc);
}
}
Node& Graph::getNode(int nodeId) {
return nodes.at(nodeId);
}
const Node& Graph::getNode(int nodeId) const {
return nodes.at(nodeId);
}
const std::vector& Graph::getArcs(int nodeId) const {
return adjacencyList.at(nodeId);
}
bool Graph::nodeExists(int nodeId) const {
return nodes.find(nodeId) != nodes.end();
}
bool Graph::arcExists(int startNodeID, int endNodeID) const {
auto it = adjacencyList.find(startNodeID);
if (it != adjacencyList.end()) {
return std::any_of(it->second.begin(), it->second.end(), [endNodeID](const Arc& arc) {
return arc.getEndNodeID() == endNodeID;
});
}
return false;
}
const std::unordered_map Graph::getAllNodes() const {
return nodes;
}
Код: Выделить всё
#include "Node.h"
Node::Node(int id, const std::string& name, double latitude, double longitude)
: id(id), name(name)
{
Utility::LLtoUTM(latitude, longitude, y, x);
}
//Setting "getters" as const as they're not changing once set
int Node::getId() const
{
return id;
}
std::string Node::getName() const
{
return name;
}
double Node::getX() const
{
return x;
}
double Node::getY() const
{
return y;
}
Код: Выделить всё
#include "Arc.h"
Arc::Arc(int startNodeID, int endNodeID, TransportMode transportMode, double distance)
: startNodeID(startNodeID), endNodeID(endNodeID), transportMode(transportMode), distance(distance) {}
int Arc::getStartNodeID() const {
return startNodeID;
}
int Arc::getEndNodeID() const {
return endNodeID;
}
TransportMode Arc::getTransportMode() const {
return transportMode;
}
double Arc::getDistance() const {
return distance;
}
void Arc::setDistance(double dist) {
distance = dist;
}
Как видите, для хранения узлов и дуг используются неупорядоченные карты. Я уже реализовал метод расчета самого дальнего расстояния между двумя узлами в Network.cpp. Имейте в виду, что это работает безупречно:
Код: Выделить всё
bool Navigation::maxDist(const std::string& params) {
double maxDistance = 0.0;
std::string farthestNodes;
const auto& nodes = networkGraph.getAllNodes(); // Ensure this returns a reference to the map
for (auto it1 = nodes.begin(); it1 != nodes.end(); ++it1) {
for (auto it2 = std::next(it1); it2 != nodes.end(); ++it2) {
// Calculate Euclidean distance between nodes in meters, then convert to kilometers
double dx = it2->second.getX() - it1->second.getX();
double dy = it2->second.getY() - it1->second.getY();
double squaredDistance = dx * dx + dy * dy;
if (squaredDistance > maxDistance) {
maxDistance = squaredDistance;
farthestNodes = it1->second.getName() + " to " + it2->second.getName();
}
}
}
maxDistance = sqrt(maxDistance) / 1000.0; // Convert from meters to kilometers
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/78450254/why-is-my-program-saying-that-a-memory-location-is-out-of-bounds-in-an-unordered[/url]
1715193781
Anonymous
В настоящее время я пишу консольную программу на C++, которая строит сеть/граф узлов и дуг, соединяющихся друг с другом с помощью неупорядоченных карт. Цель приложения — продемонстрировать «наиболее эффективный» способ обработки команд и получения информации из сети/графа. Я приложил [схему аналогичного примера].(https://i.sstatic.net/51FY0RHO.png). Ниже приведена моя BuildNetwork() метод в моем файле Network.cpp, а также в моих классах Graph.cpp, Node.cpp и Arc.cpp, чтобы вы могли получить представление о том, как моя сеть построен: [code]bool Navigation::BuildNetwork(const std::string& fileNamePlaces, const std::string& fileNameLinks) { std::ifstream finPlaces(fileNamePlaces), finLinks(fileNameLinks); if (!finPlaces || !finLinks) return false; std::string line; // Parse Places while (getline(finPlaces, line)) { std::istringstream iss(line); std::string name, idStr, latitudeStr, longitudeStr; if (getline(iss, name, ',') && getline(iss, idStr, ',') && getline(iss, latitudeStr, ',') && getline(iss, longitudeStr)) { int id = std::stoi(idStr); double latitude = std::stod(latitudeStr), longitude = std::stod(longitudeStr); Node node(id, name, latitude, longitude); networkGraph.addNode(node); } } // Parse Links while (getline(finLinks, line)) { std::istringstream iss(line); std::string startIdStr, endIdStr, modeStr; if (getline(iss, startIdStr, ',') && getline(iss, endIdStr, ',') && getline(iss, modeStr)) { int startNodeId = std::stoi(startIdStr), endNodeId = std::stoi(endIdStr); TransportMode mode = parseTransportMode(modeStr); Arc arc(startNodeId, endNodeId, mode); networkGraph.addArc(startNodeId, arc); } } return true; } // Helper function to parse string to TransportMode TransportMode Navigation::parseTransportMode(const std::string& modeStr) { static const std::unordered_map modeMap = { {"Ship", TransportMode::Ship}, {"Rail", TransportMode::Rail}, {"Bus", TransportMode::Bus}, {"Car", TransportMode::Car}, {"Bike", TransportMode::Bike}, {"Foot", TransportMode::Foot} }; auto it = modeMap.find(modeStr); if (it != modeMap.end()) return it->second; return TransportMode::Foot; // Default or error case } [/code] [code]#include "Graph.h" Graph::Graph() {} Graph::~Graph() {} void Graph::addNode(const Node& node) { nodes[node.getId()] = node; } void Graph::addArc(int startNodeID, const Arc& arc) { if (nodeExists(startNodeID) && nodeExists(arc.getEndNodeID())) { if (adjacencyList.find(startNodeID) == adjacencyList.end()) { adjacencyList[startNodeID] = std::vector(); // Initialize if not already } adjacencyList[startNodeID].push_back(arc); } } Node& Graph::getNode(int nodeId) { return nodes.at(nodeId); } const Node& Graph::getNode(int nodeId) const { return nodes.at(nodeId); } const std::vector& Graph::getArcs(int nodeId) const { return adjacencyList.at(nodeId); } bool Graph::nodeExists(int nodeId) const { return nodes.find(nodeId) != nodes.end(); } bool Graph::arcExists(int startNodeID, int endNodeID) const { auto it = adjacencyList.find(startNodeID); if (it != adjacencyList.end()) { return std::any_of(it->second.begin(), it->second.end(), [endNodeID](const Arc& arc) { return arc.getEndNodeID() == endNodeID; }); } return false; } const std::unordered_map Graph::getAllNodes() const { return nodes; } [/code] [code]#include "Node.h" Node::Node(int id, const std::string& name, double latitude, double longitude) : id(id), name(name) { Utility::LLtoUTM(latitude, longitude, y, x); } //Setting "getters" as const as they're not changing once set int Node::getId() const { return id; } std::string Node::getName() const { return name; } double Node::getX() const { return x; } double Node::getY() const { return y; } [/code] [code]#include "Arc.h" Arc::Arc(int startNodeID, int endNodeID, TransportMode transportMode, double distance) : startNodeID(startNodeID), endNodeID(endNodeID), transportMode(transportMode), distance(distance) {} int Arc::getStartNodeID() const { return startNodeID; } int Arc::getEndNodeID() const { return endNodeID; } TransportMode Arc::getTransportMode() const { return transportMode; } double Arc::getDistance() const { return distance; } void Arc::setDistance(double dist) { distance = dist; } [/code] Как видите, для хранения узлов и дуг используются неупорядоченные карты. Я уже реализовал метод расчета самого дальнего расстояния между двумя узлами в Network.cpp. Имейте в виду, что это работает безупречно: [code]bool Navigation::maxDist(const std::string& params) { double maxDistance = 0.0; std::string farthestNodes; const auto& nodes = networkGraph.getAllNodes(); // Ensure this returns a reference to the map for (auto it1 = nodes.begin(); it1 != nodes.end(); ++it1) { for (auto it2 = std::next(it1); it2 != nodes.end(); ++it2) { // Calculate Euclidean distance between nodes in meters, then convert to kilometers double dx = it2->second.getX() - it1->second.getX(); double dy = it2->second.getY() - it1->second.getY(); double squaredDistance = dx * dx + dy * dy; if (squaredDistance > maxDistance) { maxDistance = squaredDistance; farthestNodes = it1->second.getName() + " to " + it2->second.getName(); } } } maxDistance = sqrt(maxDistance) / 1000.0; // Convert from meters to kilometers std::cout Подробнее здесь: [url]https://stackoverflow.com/questions/78450254/why-is-my-program-saying-that-a-memory-location-is-out-of-bounds-in-an-unordered[/url]