Jacob
Jacob

Reputation: 11

How to make an Adjacency List using a vector of vector pair in C++?

I'm trying to create an Adjacency list using a vector of vector pair, and whenever I run the code it stops working. For now, I'm only trying to add the first pair in the Adjacency List "AdjList". Is there a better way or any modifications to do it ?

#include <iostream>
#include <vector>
using namespace std;
typedef pair<int, int> ii;
typedef vector<ii> vii;
vector <vii> AdjList;

int main()
{
    ii v= make_pair(5,4);
    AdjList[0][0]=v;
    cout << v.first<< endl;
}

Upvotes: 1

Views: 1753

Answers (2)

Red.Wave
Red.Wave

Reputation: 4225

You'd better use std::set or std::unordered_set:

std::set<std::pair<int,int>> adj_list;
adj_list.emplace(0,0);
adj_list.emplace(0,1);
for(auto& p:adj_list)
    std::cout<<p.first<<"-"<<p.second<<std::endl;

Upvotes: 0

masoud
masoud

Reputation: 56479

You're assigning a value to an empty vector:

AdjList[0][0] = v; // Problematic

Try to use std::vector::push_back or resize the size of two nested vectors.

Another way is using std::array if you know the size of the graph:

const int N = 10;

std::array<std::array<int, N>, N>  AdjList;

...

AdjList[0][0] = 1;

Upvotes: 2

Related Questions