How to store the data for multiple objectives in Shortest path search Algorithms in C++?

Improve Article

Save Article

Like Article

Improve Article

Save Article

There are several ways to store the data for multiple objectives in shortest-path search algorithms in C++. 

One way is to use a data structure such as a priority queue or a heap that allows you to store the data in a sorted manner, with the elements being ordered according to their cost.

For example, use a std::priority_queue from the C++ Standard Template Library (STL) to store the data for your shortest path search algorithm. The priority queue allows you to insert elements with a certain priority, and it will automatically maintain the queue in a sorted order based on the priority of the elements.

Here is an example of how to use a priority queue to store the data for a shortest-path search algorithm in C++:

C++

#include <iostream>

#include <queue>

#include <vector>

struct Node {

    int id;

    int cost;

};

  

struct Compare {

    bool operator()(const Node& lhs, const Node& rhs)

    {

        return lhs.cost > rhs.cost;

    }

};

  

std::priority_queue<Node, std::vector<Node>, Compare> pq;

  

int main()

{

  

    

    pq.push({ 1, 5 });

    pq.push({ 2, 2 });

    pq.push({ 3, 8 });

    pq.push({ 4, 1 });

  

    

    

    

    

    while (!pq.empty()) {

        Node node = pq.top();

        pq.pop();

        std::cout << "Node ID: " << node.id

                  << ", Cost: " << node.cost << std::endl;

    }

    return 0;

}

Output
Node ID: 4, Cost: 1
Node ID: 2, Cost: 2
Node ID: 1, Cost: 5
Node ID: 3, Cost: 8

Alternatively, you could use a different data structure, such as a std::map or a std::unordered_map, to store the data for your shortest path search algorithm. These data structures allow you to store the data in a key-value format, where the key is the node ID and the value is the cost of the node. You can then iterate through the map and extract the nodes in the order that you desire.

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: