c++ - 如何在 C++ 中使用 vector 对 vector 制作邻接列表?

标签 c++ list vector graph std-pair

我正在尝试使用 vector 对 vector 创建邻接列表,但每当我运行代码时它都会停止工作。现在,我只是想在邻接列表“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;
}

最佳答案

您正在为一个空 vector 赋值:

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

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

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

const int N = 10;

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

...

AdjList[0][0] = 1;

关于c++ - 如何在 C++ 中使用 vector 对 vector 制作邻接列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16615873/

相关文章:

c++ - 如何创建计时器? (每 X 秒/分钟/小时做某事)

c++ - 尝试在 R 中使用 sourceCpp 进行编译时出错

python - 在嵌套列表python中连接项目

python - 将列表压缩成字符串 : ['z' ,'y' ,'x' . ..] -> 'zyx...' ? python (2.7.1)

c++ - vector 析构函数在 _CrtIsValidHeapPointer 处失败

c++ - vector 数组 C++ - 添加元素时的奇怪行为

c++ - 对类使用 C 内在函数和内存对齐困难

c++ - Botan SSL/TLS 示例或起点

python - 列表的最大值(字符串项)

C++。将 csv 文件加载到 2D vector