c++ - 如何分配一个二维 vector ?

标签 c++ algorithm c++11 data-structures stdvector

我在一个问题中使用了 dfs,但直到现在我还没有在 main 中调用 dfs,我的程序崩溃了。最近我在用 c 编程,现在我切换到 cpp。所以我是 cpp 的新手。

我知道我在 vector 中哪里做错了请告诉我可以改进什么。 我知道 vector 可以自动增加那里的大小。

#include<iostream>
#include<vector>
using namespace std;
const int MAX = 100000;

bool visited[MAX] = { 0 };
int intime[MAX];
int outtime[MAX];

int timer = 0;
void dfs(vector<vector<int>> graph, int v)
{
    visited[v] = true;
    timer++;
    intime[v] = timer;
    vector<int>::iterator it = graph[v].begin();
    while (it != graph[v].end()) {
        if (visited[*it] == false)
        {
            dfs(graph, *it);
        }
        it++;
    }
    ++timer;
    outtime[v] = timer;
}

int main()
{
    vector<vector<int>> graph;
    graph[1].push_back(2);
    graph[1].push_back(3);
    graph[3].push_back(6);
    graph[2].push_back(4);
    graph[2].push_back(5);
    graph[5].push_back(7);
    graph[5].push_back(8);
    graph[5].push_back(9);
    system("pause");
}

最佳答案

您的程序因访问未分配的内存而崩溃。正确的做法是

std::vector<std::vector<int>> graph(5); // allocates 5 rows of vector of vectors
                                   ^^^^

其次,在 C++ 中,数组索引从 0 开始到 n-1。因此你需要

graph[0].push_back(2);  // element at (0,0)
graph[0].push_back(3);  // element at (0,1)
graph[1].push_back(6);  // element at (1,0)
graph[1].push_back(4);  // element at (1,1)
....

或者,您可以使用 aggregate initialization 直接初始化 vector 的 vector .

std::vector<std::vector<int>> graph
{
    {2, 3},   // first row of vector
    {4, 5},   // second row of vector
    {6},      // third row of vector
    {7, 8, 9} // forth row of vector
};

emplace每行 vector 到 vector 的 vector

using Row = std::vector<int>;
std::vector<Row> graph;
graph.emplace_back(Row{ 2, 3 });
graph.emplace_back(Row{ 4, 5 });
graph.emplace_back(Row{ 6 });
graph.emplace_back(Row{7, 8, 9});

关于c++ - 如何分配一个二维 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53501717/

相关文章:

C++ - 你能将一个静态库构建到另一个静态库中吗?

algorithm - 寻找二叉树最大深度时的最坏情况

c++ - 是否有任何boost::asio异步调用会自动超时?

c++ - AIX 服务器中的 g++ 编译 - 抛出核心转储

c# - 将小数简化为分数的算法

c++ - 寻找哈希函数/Ordered Int/to/Shuffled Int/

c++ - 赋值运算符是否应该观察被赋值对象的右值?

c++ - 带有 std::thread 和 std::chrono 的基本计时器

c++ - const_cast 是如何工作的?

c++ - boost::TIME_UTC(_) 具有不同的 boost 版本