【问题标题】:How to allocate a 2D vector?如何分配二维向量?
【发布时间】:2023-03-10 00:05:02
【问题描述】:

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

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

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

【问题讨论】:

  • graph[1] after vector&lt;vector&lt;int&gt;&gt; graph; 是未定义的行为,由于不存在元素访问。
  • 我声明一个二维向量
  • 即vector的vector
  • @humblefool 您正在声明一个空的二维向量,然后访问不存在的元素。
  • @humblefool "这里的行大小无所谓,可以根据需要扩展" 仅当使用push_backemplace_backresize时。考虑重新阅读std::vector::operator[]的文档。

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


【解决方案1】:

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

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

其次,在 C++ 中,数组索引从 0n-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 直接初始化向量的向量

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每行向量到向量的向量

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

【讨论】:

    【解决方案2】:

    按照您声明的方式,向量的大小为零。

    你可以做的是用大小声明向量。

    int v = 10;
    std::vector<std::vector<int>>graph(v);
    graph[1].push_back(2);
    

    这会起作用。

    【讨论】:

      猜你喜欢
      • 2015-06-10
      • 2016-08-11
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 2014-06-11
      相关资源
      最近更新 更多