Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -----------------------------------------------------------------------
- domain.h
- -----------------------------------------------------------------------
- #pragma once
- #include "transport_catalogue.h"
- #include <algorithm>
- #include <vector>
- namespace transport_catalogue {
- namespace detail {
- namespace bus {
- struct BusQueryResult{
- std::string_view name;
- bool not_found;
- int stops_on_route;
- int unique_stops;
- int route_length;
- double curvature;
- };
- void show_terminal(BusQueryResult bus_info, std::ostream& output);
- BusQueryResult query(TransportCatalogue& catalogue, std::string_view str);
- }//end namespace bus
- namespace stop {
- struct StopQueryResult{
- std::string_view name;
- bool not_found;
- std::vector <std::string> buses_name;
- };
- void show_terminal(const StopQueryResult& stop_info, std::ostream& output);
- StopQueryResult query(TransportCatalogue& catalogue, std::string_view stop_name);
- }//end namespace stop
- void execute_query(TransportCatalogue& catalogue, std::string_view str);
- void parse_and_execute_queries(TransportCatalogue& catalogue);
- }//end namespace detail
- }//end namespace transport_catalogue
- -----------------------------------------------------------------------
- domain.cpp
- -----------------------------------------------------------------------
- #include "domain.h"
- namespace transport_catalogue {
- namespace detail {
- namespace bus {
- void show_terminal(BusQueryResult bus_info, std::ostream& output) {
- if (bus_info.not_found) {
- output << "Bus " << bus_info.name << ": not found" << std::endl;
- } else {
- output << "Bus " << bus_info.name << ": "
- << bus_info.stops_on_route << " stops on route, "
- << bus_info.unique_stops << " unique stops, "
- << bus_info.route_length << " route length, "
- << std::setprecision(6) << bus_info.curvature
- << " curvature" << std::endl;
- }
- }
- BusQueryResult query(TransportCatalogue& catalogue, std::string_view bus_name) {
- BusQueryResult bus_info;
- Bus* bus = catalogue.get_bus(bus_name);
- if (bus != nullptr) {
- bus_info.name = bus->name;
- bus_info.not_found = false;
- bus_info.stops_on_route = bus->stops.size();
- bus_info.unique_stops = catalogue.get_uniq_stops(bus).size();
- bus_info.route_length = bus->route_length;
- bus_info.curvature = double(catalogue.get_distance_to_bus(bus)
- /catalogue.get_length(bus));
- } else {
- bus_info.name = bus_name;
- bus_info.not_found = true;
- }
- return bus_info;
- }
- }//end namespace bus
- namespace stop {
- void show_terminal(const StopQueryResult& stop_info, std::ostream& output) {
- if (stop_info.not_found) {
- output << "Stop " << stop_info.name << ": not found" << std::endl;
- } else {
- if (stop_info.buses_name.size() == 0) {
- output << "Stop " << stop_info.name << ": no buses" << std::endl;
- } else {
- output << "Stop " << stop_info.name << ": buses ";
- for (std::string_view bus_name : stop_info.buses_name) {
- output << bus_name;
- output << " ";
- }
- output << std::endl;
- }
- }
- }
- StopQueryResult query(TransportCatalogue& catalogue, std::string_view stop_name) {
- std::unordered_set<const Bus*> unique_buses;
- StopQueryResult stop_info;
- Stop* stop = catalogue.get_stop(stop_name);
- if (stop != NULL) {
- stop_info.name = stop->name;
- stop_info.not_found = false;
- unique_buses = catalogue.stop_get_uniq_buses(stop);
- if (unique_buses.size() > 0) {
- for (const Bus* bus : unique_buses) {
- stop_info.buses_name.push_back(bus->name);
- }
- std::sort(stop_info.buses_name.begin(), stop_info.buses_name.end());
- }
- } else {
- stop_info.name = stop_name;
- stop_info.not_found = true;
- }
- return stop_info;
- }
- }//end namespace stop
- void execute_query(TransportCatalogue& catalogue, std::string_view str) {
- if (str.substr(0, 3) == "Bus") {
- bus::show_terminal(bus::query(catalogue, str), std::cout);
- } else if (str.substr(0, 4) == "Stop") {
- stop::show_terminal(stop::query(catalogue, str), std::cout);
- } else {
- std::cout << "Error query" << std::endl;
- }
- }
- void parse_and_execute_queries(TransportCatalogue& catalogue) {
- std::vector<std::string> query;
- query.push_back("Bus 114");
- query.push_back("Stop Морской вокзал");
- query.push_back("Stop Ривьерский мост");
- for (auto& strr : query) {
- execute_query(catalogue, strr);
- }
- }
- }//end namespace detail
- }//end namespace transport_catalogue
- -----------------------------------------------------------------------
- geo.h
- -----------------------------------------------------------------------
- #pragma once
- #include <cmath>
- namespace transport_catalogue {
- namespace detail {
- namespace geo {
- const int EARTH_RADIUS = 6371000;
- const double PI = 3.1415926535;
- struct Coordinates {
- double latitude;
- double longitude;
- bool operator==(const Coordinates& other) const {
- return latitude == other.latitude && longitude == other.longitude;
- }
- bool operator!=(const Coordinates& other) const {
- return !(*this == other);
- }
- };
- double compute_distance(Coordinates start, Coordinates end);
- }//end namespace geo
- }//end namespace detail
- }//end namespace transport_catalogue
- -----------------------------------------------------------------------
- geo.cpp
- -----------------------------------------------------------------------
- #define _USE_MATH_DEFINES
- #include "geo.h"
- #include <cmath>
- namespace transport_catalogue {
- namespace detail {
- namespace geo {
- double compute_distance(Coordinates start, Coordinates end) {
- using namespace std;
- if (!(start == end)) {
- const double dr = PI / 180.;
- return acos(sin(start.latitude * dr) * sin(end.latitude * dr)
- + cos(start.latitude * dr) * cos(end.latitude * dr)
- * cos(abs(start.longitude - end.longitude) * dr)) * EARTH_RADIUS;
- } else {
- return 0.0;
- }
- }
- }//end namespace geo
- }//end namespace detail
- }//end namespace transport_catalogue
- -----------------------------------------------------------------------
- json.h
- -----------------------------------------------------------------------
- #pragma once
- /*
- * Место для вашей JSON-библиотеки
- */
- #pragma once
- #include <iostream>
- #include <map>
- #include <string>
- #include <vector>
- #include <variant>
- namespace transport_catalogue {
- namespace detail {
- namespace json {
- class Node;
- using Dict = std::map<std::string, Node>;
- using Array = std::vector<Node>;
- class ParsingError : public std::runtime_error {
- public:
- using runtime_error::runtime_error;
- };
- class Node {
- public:
- using Value = std::variant<std::nullptr_t, Array, Dict, bool, int, double, std::string>;
- Node() = default;
- Node(bool value);
- Node(Array array);
- Node(Dict map);
- Node(int value);
- Node(std::string value);
- Node(std::nullptr_t);
- Node(double value);
- const Array& AsArray() const;
- const Dict& AsMap() const;
- int AsInt() const;
- double AsDouble() const;
- bool AsBool() const;
- const std::string& AsString() const;
- bool IsNull() const;
- bool IsInt() const;
- bool IsDouble() const;
- bool IsPureDouble() const;
- bool IsBool() const;
- bool IsString() const;
- bool IsArray() const;
- bool IsMap() const;
- const Value& GetValue() const { return value_; };
- private:
- Value value_;
- };
- inline bool operator==(const Node& lhs, const Node& rhs) {
- return lhs.GetValue() == rhs.GetValue();
- }
- inline bool operator!=(const Node& lhs, const Node& rhs) {
- return !(lhs == rhs);
- }
- class Document {
- public:
- explicit Document(Node root);
- Document() = default;
- const Node& GetRoot() const;
- private:
- Node root_;
- };
- Document Load(std::istream& input);
- inline bool operator==(const Document& lhs, const Document& rhs) {
- return lhs.GetRoot() == rhs.GetRoot();
- }
- inline bool operator!=(const Document& lhs, const Document& rhs) {
- return !(lhs == rhs);
- }
- void Print(const Document& doc, std::ostream& output);
- }//end namespace json
- }//end namespace detail
- }//end namespace transport_catalogue
- -----------------------------------------------------------------------
- json.cpp
- -----------------------------------------------------------------------
- #include "json.h"
- using namespace std;
- namespace transport_catalogue {
- namespace detail {
- namespace json {
- namespace {
- Node LoadNode(istream& input);
- std::string LoadLiteral(std::istream& input) {
- std::string str;
- while (std::isalpha(input.peek())) {
- str.push_back(static_cast<char>(input.get()));
- }
- return str;
- }
- Node LoadArray(std::istream& input) {
- std::vector<Node> result;
- for (char current_char; input >> current_char && current_char != ']';) {
- if (current_char != ',') {
- input.putback(current_char);
- }
- result.push_back(LoadNode(input));
- }
- if (!input) {
- throw ParsingError("Array parsing error"s);
- }
- return Node(result);
- }
- Node LoadNull(std::istream& input) {
- if (auto literal = LoadLiteral(input); literal == "null"sv) {
- return Node{ nullptr };
- } else {
- throw ParsingError("Failed to parse '"s + literal + "' as null"s);
- }
- }
- Node LoadBool(std::istream& input) {
- const auto str = LoadLiteral(input);
- if (str == "true"sv) {
- return Node{ true };
- } else if (str == "false"sv) {
- return Node{ false };
- } else {
- throw ParsingError("Failed to parse '"s + str + "' as bool"s);
- }
- }
- Node LoadNumber(std::istream& input) {
- std::string parsed_num;
- auto read_char = [&parsed_num, &input] {
- parsed_num += static_cast<char>(input.get());
- if (!input) {
- throw ParsingError("Failed to read number from stream"s);
- }
- };
- auto read_digits = [&input, read_char] {
- if (!std::isdigit(input.peek())) {
- throw ParsingError("A digit is expected"s);
- }
- while (std::isdigit(input.peek())) {
- read_char();
- }
- };
- if (input.peek() == '-') {
- read_char();
- }
- if (input.peek() == '0') {
- read_char();
- } else {
- read_digits();
- }
- bool is_int = true;
- if (input.peek() == '.') {
- read_char();
- read_digits();
- is_int = false;
- }
- if (int current_char = input.peek(); current_char == 'e' || current_char == 'E') {
- read_char();
- if (current_char = input.peek(); current_char == '+' || current_char == '-') {
- read_char();
- }
- read_digits();
- is_int = false;
- }
- try {
- if (is_int) {
- try {
- return Node(std::stoi(parsed_num));
- } catch (...) {
- }
- }
- return Node(std::stod(parsed_num));
- } catch (...) {
- throw ParsingError("Failed to convert "s + parsed_num + " to number"s);
- }
- }
- Node LoadString(std::istream& input) {
- auto it = std::istreambuf_iterator<char>(input);
- auto end = std::istreambuf_iterator<char>();
- std::string str;
- while (true) {
- if (it == end) {
- throw ParsingError("String parsing error");
- }
- const char current_char = *it;
- if (current_char == '"') {
- ++it;
- break;
- } else if (current_char == '\\') {
- ++it;
- if (it == end) {
- throw ParsingError("String parsing error");
- }
- const char escaped_char = *(it);
- switch (escaped_char) {
- case 'n':
- str.push_back('\n');
- break;
- case 't':
- str.push_back('\t');
- break;
- case 'r':
- str.push_back('\r');
- break;
- case '"':
- str.push_back('"');
- break;
- case '\\':
- str.push_back('\\');
- break;
- default:
- throw ParsingError("Unrecognized escape sequence \\"s + escaped_char);
- }
- } else if (current_char == '\n' || current_char == '\r') {
- throw ParsingError("Unexpected end of line"s);
- } else {
- str.push_back(current_char);
- }
- ++it;
- }
- return Node(str);
- }
- Node LoadDict(std::istream& input) {
- Dict dict;
- for (char current_char; input >> current_char && current_char != '}';) {
- if (current_char == '"') {
- std::string key = LoadString(input).AsString();
- if (input >> current_char && current_char == ':') {
- if (dict.find(key) != dict.end()) {
- throw ParsingError("Duplicate key '"s + key + "' have been found");
- }
- dict.emplace(std::move(key), LoadNode(input));
- } else {
- throw ParsingError(": is expected but '"s + current_char + "' has been found"s);
- }
- } else if (current_char != ',') {
- throw ParsingError(R"(',' is expected but ')"s + current_char + "' has been found"s);
- }
- }
- if (!input) {
- throw ParsingError("Dictionary parsing error"s);
- }
- return Node(dict);
- }
- Node LoadNode(std::istream& input) {
- char c;
- if (!(input >> c)) {
- throw ParsingError(""s);
- }
- switch (c) {
- case '[':
- return LoadArray(input);
- case '{':
- return LoadDict(input);
- case '"':
- return LoadString(input);
- case 't': case 'f':
- input.putback(c);
- return LoadBool(input);
- case 'n':
- input.putback(c);
- return LoadNull(input);
- default:
- input.putback(c);
- return LoadNumber(input);
- }
- }
- } // namespace
- Node::Node(Array array) :
- value_(std::move(array)) {
- }
- Node::Node(std::nullptr_t) :
- Node() {}
- Node::Node(bool value)
- : value_(value) {
- }
- Node::Node(Dict map)
- : value_(move(map)) {
- }
- Node::Node(int value)
- : value_(value) {
- }
- Node::Node(string value)
- : value_(move(value)) {
- }
- Node::Node(double value)
- : value_(value) {
- }
- const Array& Node::AsArray() const {
- using namespace std::literals;
- if (!IsArray()) {
- throw std::logic_error("Error: not array"s);
- }
- return std::get<Array>(value_);
- }
- const Dict& Node::AsMap() const {
- using namespace std::literals;
- if (!IsMap()) {
- throw std::logic_error("Error: not dict"s);
- }
- return std::get<Dict>(value_);
- }
- const string& Node::AsString() const {
- using namespace std::literals;
- if (!IsString()) {
- throw std::logic_error("Error: not string"s);
- }
- return std::get<std::string>(value_);
- }
- int Node::AsInt() const {
- using namespace std::literals;
- if (!IsInt()) {
- throw std::logic_error("Error: not int"s);
- }
- return std::get<int>(value_);
- }
- double Node::AsDouble() const {
- using namespace std::literals;
- if (!IsDouble()) {
- throw std::logic_error("Error: not double"s);
- }
- if(IsPureDouble()){
- return std::get<double>(value_);
- }
- else{
- return AsInt();
- }
- }
- bool Node::AsBool() const {
- using namespace std::literals;
- if (!IsBool()) {
- throw std::logic_error("Error: not bool"s);
- }
- return std::get<bool>(value_);
- }
- bool Node::IsNull() const {
- return std::holds_alternative<std::nullptr_t>(value_);
- }
- bool Node::IsInt() const {
- return std::holds_alternative<int>(value_);
- }
- bool Node::IsDouble() const {
- return IsInt() || IsPureDouble();
- }
- bool Node::IsPureDouble() const {
- return std::holds_alternative<double>(value_);
- }
- bool Node::IsBool() const {
- return std::holds_alternative<bool>(value_);
- }
- bool Node::IsString() const {
- return std::holds_alternative<std::string>(value_);
- }
- bool Node::IsArray() const {
- return std::holds_alternative<Array>(value_);
- }
- bool Node::IsMap() const {
- return std::holds_alternative<Dict>(value_);
- }
- Document::Document(Node root)
- : root_(move(root)) {
- }
- const Node& Document::GetRoot() const {
- return root_;
- }
- Document Load(istream& input) {
- return Document{LoadNode(input)};
- }
- struct PrintContext {
- std::ostream& out;
- int indent_step = 4;
- int indent = 0;
- void PrintIndent() const {
- for (int i = 0; i < indent; ++i) {
- out.put(' ');
- }
- }
- [[nodiscard]] PrintContext Indented() const {
- return { out, indent_step, indent_step + indent };
- }
- };
- void PrintNode(const Node& node, const PrintContext& ctx);
- template <typename Value>
- void PrintValue(const Value& value, const PrintContext& ctx) {
- ctx.out << value;
- }
- void PrintString(const std::string& value, std::ostream& out) {
- out.put('"');
- for (const char current_char : value) {
- switch (current_char) {
- case '\r':
- out << R"(\r)";
- break;
- case '\n':
- out << R"(\n)";
- break;
- case '"':
- out << R"(\")";
- break;
- case '\\':
- out << R"(\\)";
- break;
- default:
- out.put(current_char);
- break;
- }
- }
- out.put('"');
- }
- template <>
- void PrintValue<std::string>(const std::string& value, const PrintContext& ctx) {
- PrintString(value, ctx.out);
- }
- void PrintValue(const std::nullptr_t&, const PrintContext& ctx) {
- ctx.out << "null"s;
- }
- void PrintValue(bool value, const PrintContext& ctx) {
- ctx.out << std::boolalpha << value;
- }
- [[maybe_unused]] void PrintValue(Array nodes, const PrintContext& ctx) {
- std::ostream& out = ctx.out;
- out << "[\n"sv;
- bool first = true;
- auto inner_ctx = ctx.Indented();
- for (const Node& node : nodes) {
- if (first) {
- first = false;
- } else {
- out << ",\n"sv;
- }
- inner_ctx.PrintIndent();
- PrintNode(node, inner_ctx);
- }
- out.put('\n');
- ctx.PrintIndent();
- out.put(']');
- }
- [[maybe_unused]] void PrintValue(Dict nodes, const PrintContext& ctx) {
- std::ostream& out = ctx.out;
- out << "{\n"sv;
- bool first = true;
- auto inner_ctx = ctx.Indented();
- for (const auto& [key, node] : nodes) {
- if (first) {
- first = false;
- } else {
- out << ",\n"sv;
- }
- inner_ctx.PrintIndent();
- PrintString(key, ctx.out);
- out << ": "sv;
- PrintNode(node, inner_ctx);
- }
- out.put('\n');
- ctx.PrintIndent();
- out.put('}');
- }
- void PrintNode(const Node& node, const PrintContext& ctx) {
- std::visit(
- [&ctx](const auto& value) {
- PrintValue(value, ctx);
- },
- node.GetValue());
- }
- void Print(const Document& doc, std::ostream& output) {
- PrintNode(doc.GetRoot(), PrintContext{ output });
- }
- }//end namespace json
- }//end namespace detail
- }//end namespace transport_catalogue
- -----------------------------------------------------------------------
- json_reader.h
- -----------------------------------------------------------------------
- #pragma once
- #include "json.h"
- #include "transport_catalogue.h"
- #include "domain.h"
- namespace transport_catalogue {
- namespace detail {
- namespace json {
- using namespace transport_catalogue::detail::stop;
- using namespace transport_catalogue::detail::bus;
- struct StatRequest {
- int id;
- std::string type;
- std::string name;
- };
- void ParseNode(const Node& root, TransportCatalogue& catalogue, std::vector<StatRequest>& stat_request);
- void Parse(Document& doc, TransportCatalogue& catalogue, std::vector<StatRequest>& stat_request);
- void ParseNodeBase(const Node& root, TransportCatalogue& catalogue);
- void ParceNodeStat(const Node& root, std::vector<StatRequest>& stat_request);
- Stop ParseNodeStop(Node& node);
- std::vector<Distance> ParseNodeDistances(Node& node, TransportCatalogue& catalogue);
- Bus ParseNodeBus(Node& node, TransportCatalogue& catalogue);
- Document ExecuteQueries(TransportCatalogue& catalogue, std::vector<StatRequest>& stat_requests);
- Node ExecuteMakeNodeStop(int id_request, StopQueryResult query_result);
- Node ExecuteMakeNodeBus(int id_request, BusQueryResult query_result);
- }//end namespace json
- }//end namespace detail
- }//end namespace transport_catalogue
- -----------------------------------------------------------------------
- json_reader.cpp
- -----------------------------------------------------------------------
- #include "json_reader.h"
- namespace transport_catalogue {
- namespace detail {
- namespace json {
- void Parse(Document& doc, TransportCatalogue& catalogue, std::vector<StatRequest>& stat_request) {
- ParseNode(doc.GetRoot(),
- catalogue,
- stat_request);
- }
- void ParseNode(const Node& root, TransportCatalogue& catalogue, std::vector<StatRequest>& stat_request) {
- Dict root_dict;
- if (root.IsMap()) {
- root_dict = root.AsMap();
- try {
- ParseNodeBase(root_dict.at("base_requests"), catalogue);
- } catch(...) {
- std::cout << "Error: base_requests is empty";
- }
- try {
- ParceNodeStat(root_dict.at("stat_requests"), stat_request);
- } catch(...) {
- std::cout << "Error: stat_requests is empty";
- }
- } else {
- std::cout << "Error: root is not map";
- }
- }
- void ParseNodeBase(const Node& root, TransportCatalogue& catalogue) {
- Array base_requests;
- Dict req_map;
- Node req_node;
- std::vector<Node> buses;
- std::vector<Node> stops;
- if (root.IsArray()) {
- base_requests = root.AsArray();
- for (Node& node : base_requests) {
- if (node.IsMap()) {
- req_map = node.AsMap();
- try {
- req_node = req_map.at("type");
- if (req_node.IsString()) {
- if (req_node.AsString() == "Bus") {
- buses.push_back(req_map);
- } else if (req_node.AsString() == "Stop") {
- stops.push_back(req_map);
- } else {
- std::cout << "Error: base_requests have bad type";
- }
- }
- } catch(...) {
- std::cout << "Error: base_requests not have type value";
- }
- }
- }
- for (auto stop : stops) {
- catalogue.add_stop(ParseNodeStop(stop));
- }
- for (auto stop : stops) {
- catalogue.add_distance(ParseNodeDistances(stop, catalogue));
- }
- for (auto bus : buses) {
- catalogue.add_bus(ParseNodeBus(bus, catalogue));
- }
- } else {
- std::cout << "Error: base_requests is not array";
- }
- }
- Stop ParseNodeStop(Node& node) {
- Stop stop;
- Dict stop_node;
- if (node.IsMap()) {
- stop_node = node.AsMap();
- stop.name = stop_node.at("name").AsString();
- stop.latitude = stop_node.at("latitude").AsDouble();
- stop.longitude = stop_node.at("longitude").AsDouble();
- }
- return stop;
- }
- std::vector<Distance> ParseNodeDistances(Node& node, TransportCatalogue& catalogue) {
- std::vector<Distance> distances;
- Dict stop_node;
- Dict stop_road_map;
- std::string begin_name;
- std::string last_name;
- int distance;
- if (node.IsMap()) {
- stop_node = node.AsMap();
- begin_name = stop_node.at("name").AsString();
- try {
- stop_road_map = stop_node.at("road_distances").AsMap();
- for (auto [key, value] : stop_road_map) {
- last_name = key;
- distance = value.AsInt();
- distances.push_back({catalogue.get_stop(begin_name),
- catalogue.get_stop(last_name),
- distance});
- }
- }
- catch(...) {
- std::cout << "Error: Road invalide" << std::endl;
- }
- }
- return distances;
- }
- Bus ParseNodeBus(Node& node, [[maybe_unused]] TransportCatalogue& catalogue) {
- Bus bus;
- Dict bus_node;
- Array bus_stops;
- if (node.IsMap()) {
- bus_node = node.AsMap();
- bus.name = bus_node.at("name").AsString();
- bus.is_roundtrip = bus_node.at("is_roundtrip").AsBool();
- try {
- bus_stops = bus_node.at("stops").AsArray();
- for (Node stop : bus_stops) {
- bus.stops.push_back(catalogue.get_stop(stop.AsString()));
- }
- if (!bus.is_roundtrip) {
- size_t size = bus.stops.size() - 1;
- for (size_t i = size; i > 0; i--) {
- bus.stops.push_back(bus.stops[i-1]);
- }
- }
- } catch(...) {
- std::cout << "Error: base_requests: bus: stops is empty" << std::endl;
- }
- }
- return bus;
- }
- void ParceNodeStat(const Node& node, std::vector<StatRequest>& stat_request) {
- Array stat_requests;
- Dict req_map;
- StatRequest req;
- if (node.IsArray()) {
- stat_requests = node.AsArray();
- for (Node req_node : stat_requests) {
- if (req_node.IsMap()) {
- req_map = req_node.AsMap();
- req.id = req_map.at("id").AsInt();
- req.type = req_map.at("type").AsString();
- req.name = req_map.at("name").AsString();
- stat_request.push_back(req);
- }
- }
- } else {
- std::cout << "Error: base_requests is not array";
- }
- }
- Document ExecuteQueries([[maybe_unused]] TransportCatalogue& catalogue, std::vector<StatRequest>& stat_requests) {
- std::vector<Node> result_request;
- for (StatRequest req : stat_requests) {
- if (req.type == "Stop") {
- result_request.push_back(ExecuteMakeNodeStop(req.id, stop::query(catalogue,
- req.name)));
- } else if(req.type == "Bus") {
- result_request.push_back(ExecuteMakeNodeBus(req.id,bus::query(catalogue,
- req.name)));
- }
- }
- return Document{Node{result_request}};
- }
- Node ExecuteMakeNodeStop(int id_request, StopQueryResult stop_info) {
- Dict result;
- Array buses;
- std::string str_not_found = "not found";
- if (stop_info.not_found) {
- result.emplace("request_id", Node{id_request});
- result.emplace("error_message", Node{str_not_found});
- } else {
- result.emplace("request_id", Node{id_request});
- for (std::string bus_name : stop_info.buses_name) {
- buses.push_back(Node{bus_name});
- }
- result.emplace("buses", Node{buses});
- }
- return Node{result};
- }
- Node ExecuteMakeNodeBus(int id_request, BusQueryResult bus_info) {
- Dict result;
- std::string str_not_found = "not found";
- if (bus_info.not_found) {
- result.emplace("request_id", Node{id_request});
- result.emplace("error_message", Node{str_not_found});
- } else {
- result.emplace("request_id", Node{id_request});
- result.emplace("curvature", Node{bus_info.curvature});
- result.emplace("route_length", Node{bus_info.route_length});
- result.emplace("stop_count", Node{bus_info.stops_on_route});
- result.emplace("unique_stop_count", Node{bus_info.unique_stops});
- }
- return Node{result};
- }
- }//end namespace json
- }//end namespace detail
- }//end namespace transport_catalogue
- -----------------------------------------------------------------------
- main.cpp
- -----------------------------------------------------------------------
- #include "transport_catalogue.h"
- #include "json_reader.h"
- #include "domain.h"
- using namespace std;
- using namespace transport_catalogue;
- using namespace transport_catalogue::detail;
- using namespace transport_catalogue::detail::json;
- int main() {
- std::vector<StatRequest> stat_request;
- TransportCatalogue catalogue;
- Document doc_in;
- Document doc_out;
- doc_in = json::Load(std::cin);
- json::Parse(doc_in, catalogue, stat_request);
- doc_out = json::ExecuteQueries(catalogue, stat_request);
- Print(doc_out, std::cout);
- }
- -----------------------------------------------------------------------
- map_renderer.h
- -----------------------------------------------------------------------
- empty
- -----------------------------------------------------------------------
- map_renderer.cpp
- -----------------------------------------------------------------------
- empty
- -----------------------------------------------------------------------
- request_handler.h
- -----------------------------------------------------------------------
- empty
- -----------------------------------------------------------------------
- request_handler.cpp
- -----------------------------------------------------------------------
- empty
- -----------------------------------------------------------------------
- svg.h
- -----------------------------------------------------------------------
- empty
- -----------------------------------------------------------------------
- svg.cpp
- -----------------------------------------------------------------------
- empty
- -----------------------------------------------------------------------
- transport_catalogue.h
- -----------------------------------------------------------------------
- #pragma once
- #include <deque>
- #include <string>
- #include <vector>
- #include <iomanip>
- #include <iostream>
- #include <unordered_set>
- #include <unordered_map>
- #include "geo.h"
- namespace transport_catalogue {
- struct Bus;
- struct Stop {
- std::string name;
- double latitude;
- double longitude;
- std::vector<Bus*> buses;
- };
- struct Bus {
- std::string name;
- std::vector<Stop*> stops;
- bool is_roundtrip;
- size_t route_length;
- };
- struct Distance {
- const Stop* A;
- const Stop* B;
- int distance;
- };
- struct DistanceHasher {
- std::hash<const void*> hasher;
- std::size_t operator()(const std::pair<const Stop*, const Stop*> pair_stops) const noexcept {
- auto hash_1 = static_cast<const void*>(pair_stops.first);
- auto hash_2 = static_cast<const void*>(pair_stops.second);
- return hasher(hash_1) * 17 + hasher(hash_2);
- }
- };
- typedef std::unordered_map<std::string_view, Stop*> StopMap;
- typedef std::unordered_map<std::string_view, Bus*> BusMap;
- typedef std::unordered_map<std::pair<const Stop*, const Stop*>, int, DistanceHasher> DistanceMap;
- class TransportCatalogue {
- public:
- void add_bus(Bus&& bus);
- void add_stop(Stop&& stop);
- void add_distance(const std::vector<Distance>& distances);
- Bus* get_bus(std::string_view bus_name);
- Stop* get_stop(std::string_view stop_name);
- std::unordered_set<const Bus*> stop_get_uniq_buses(Stop* stop);
- std::unordered_set<const Stop*> get_uniq_stops(Bus* bus);
- double get_length(Bus* bus);
- size_t get_distance_stop(const Stop* start, const Stop* finish);
- size_t get_distance_to_bus(Bus* bus);
- private:
- std::deque<Stop> stops;
- StopMap stopname_to_stop;
- std::deque<Bus> buses;
- BusMap busname_to_bus;
- DistanceMap distance_to_stop;
- };
- }//end namespace transport_catalogue
- -----------------------------------------------------------------------
- transport_catalogue.cpp
- -----------------------------------------------------------------------
- #include "transport_catalogue.h"
- #include <execution>
- namespace transport_catalogue {
- void TransportCatalogue::add_stop(Stop&& stop) {
- stops.push_back(std::move(stop));
- Stop* stop_buf = &stops.back();
- stopname_to_stop.insert(transport_catalogue::StopMap::value_type(stop_buf->name, stop_buf));
- }
- void TransportCatalogue::add_bus(Bus&& bus) {
- Bus* bus_buf;
- buses.push_back(std::move(bus));
- bus_buf = &buses.back();
- busname_to_bus.insert(BusMap::value_type(bus_buf->name, bus_buf));
- for (Stop* stop : bus_buf->stops) {
- stop->buses.push_back(bus_buf);
- }
- bus_buf->route_length = get_distance_to_bus(bus_buf);
- }
- void TransportCatalogue::add_distance(const std::vector<Distance>& distances) {
- for (auto distance : distances){
- auto dist_pair = std::make_pair(distance.A, distance.B);
- distance_to_stop.insert(DistanceMap::value_type(dist_pair, distance.distance));
- }
- }
- Bus* TransportCatalogue::get_bus(std::string_view bus_name) {
- if(busname_to_bus.empty()){
- return nullptr;
- }
- try{
- return busname_to_bus.at(bus_name);
- }
- catch(const std::out_of_range &e){
- return nullptr;
- }
- }
- Stop* TransportCatalogue::get_stop(std::string_view stop_name) {
- if(stopname_to_stop.empty()){
- return nullptr;
- }
- try {
- return stopname_to_stop.at(stop_name);
- } catch(const std::out_of_range &e) {
- return nullptr;
- }
- }
- std::unordered_set<const Stop*> TransportCatalogue::get_uniq_stops(Bus* bus) {
- std::unordered_set<const Stop*> unique_stops;
- unique_stops.insert(bus->stops.begin(), bus->stops.end());
- return unique_stops;
- }
- double TransportCatalogue::get_length(Bus* bus) {
- return transform_reduce(next(bus->stops.begin()),
- bus->stops.end(),
- bus->stops.begin(),
- 0.0,
- std::plus<>{},
- [](const Stop* lhs, const Stop* rhs) {
- return detail::geo::compute_distance({(*lhs).latitude,
- (*lhs).longitude}, {(*rhs).latitude,
- (*rhs).longitude});
- });
- }
- std::unordered_set<const Bus*> TransportCatalogue::stop_get_uniq_buses(Stop* stop){
- std::unordered_set<const Bus*> unique_stops;
- unique_stops.insert(stop->buses.begin(), stop->buses.end());
- return unique_stops;
- }
- size_t TransportCatalogue::get_distance_stop(const Stop* begin, const Stop* finish) {
- if(distance_to_stop.empty()){
- return 0;
- }
- try {
- auto dist_pair = std::make_pair(begin, finish);
- return distance_to_stop.at(dist_pair);
- } catch(const std::out_of_range &e) {
- try {
- auto dist_pair = std::make_pair(finish, begin);
- return distance_to_stop.at(dist_pair);
- } catch(const std::out_of_range &e) {
- return 0;
- }
- }
- }
- size_t TransportCatalogue::get_distance_to_bus(Bus* bus) {
- size_t distance = 0;
- auto stops_size = bus->stops.size() - 1;
- for (int i = 0; i < stops_size; i++) {
- distance += get_distance_stop(bus->stops[i], bus->stops[i+1]);
- }
- return distance;
- }
- }//end namespace transport_catalogue
Advertisement
Add Comment
Please, Sign In to add comment