如何在c++中使用矢量对的矢量制作邻接表

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

本文关键字:c++      更新时间:2023-10-16

我试图使用向量对的向量创建邻接列表,每当我运行代码时,它就停止工作。现在,我只尝试在邻接列表"AdjList"中添加第一对。有更好的方法或修改吗?

#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;
}

你正在给一个空向量赋值:

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

尝试使用std::vector::push_back或调整两个嵌套向量的大小。

另一种方法是使用std::array,如果你知道图形的大小:

const int N = 10;
std::array<std::array<int, N>, N>  AdjList;
...
AdjList[0][0] = 1;

您最好使用std::setstd::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;
相关文章:
  • 没有找到相关文章