【问题标题】:What's the difference between vector<vector<int>> vec and vector<vector<int>> vec(n)? [duplicate]vector<vector<int>> vec 和 vector<vector<int>> vec(n) 有什么区别? [复制]
【发布时间】:2021-11-07 10:39:35
【问题描述】:

我今天试图访问矢量元素,所以当我使用vector&lt;vector&lt;int&gt;&gt; vec 然后向它​​添加元素时。我能够访问像vec[1][2] 这样的元素。

但是当我使用vector&lt;vector&lt;int&gt;&gt; vec(n) 然后添加元素时,我无法使用vec[1][2] 访问元素。我不断收到分段错误。有谁知道我在这里错过了什么?

我在下面的代码 sn-p 的帮助下将元素添加到向量中。

int n;
cin >> n;
vector<vector<int>> vh;
int size, input;
for (int i = 0; i < n; i++)
{
    vector<int> temp;
    cin >> size;
    for (int j = 0; j < size; j++)
    {
        cin >> input;
        temp.push_back(input);
    }
    vh.push_back(temp);
}

【问题讨论】:

  • 此外,当您越界时,使用向量的任何一种尝试似乎都会导致 未定义的行为。请edit您的问题包括正确的minimal reproducible example
  • 请创建一个minimal reproducible example。问题可能在于您如何“添加元素”,但我们无法猜测您是如何做到的。
  • 您在第一种情况下创建了一个空向量,但在第二种情况下创建了一个由n 空向量组成的向量。在第一种情况下,使用第一个 [] 运算符的任何访问都会导致未定义的行为(可能包括段错误);在第二种情况下,您仍然需要在第二个向量中添加至少 3 个元素才能在使用 vec[1][2] 时获得未定义的行为(假设 n &gt;=2
  • 你是否在学习如何使用std::vector的教程?

标签: c++ c++11 vector segmentation-fault stdvector


【解决方案1】:

我想我可以猜出问题是什么......

当你使用带参数的构造函数时:

vector<vector<int>> vh(n);

您创建一个大小为n 的向量,这意味着它已经有n 元素,其中每个元素都是默认构造的vector&lt;int&gt;。这意味着每个向量都是空的

然后你推回一个新的向量:

vh.push_back(temp);

这将增加向量的大小。在一个这样的push_back 调用之后,vh 的大小将是n + 1。您添加的新向量将位于索引n,即vh[n] 是新向量。

如果在定义向量时设置了大小,那么需要使用索引和赋值来设置子向量:

vh[i] = temp;

总结一下:

  • 您要么创建一个空向量并推回新元素:

    vector<vector<int>> vh;
    

    vh.push_back(temp);
    
  • 或者你创建一个有大小的向量,并使用索引和赋值:

    vector<vector<int>> vh(n);
    

    v[i] = temp;
    

不要混合使用这些方式。


现在,当您让当前的代码正常工作(希望如此)并了解这些事情如何更好地工作时,是时候展示一种如何以更“C++-ish”的方式编写代码... :)

// The first part is much like your current code
size_t n;
std::cin >> n;
std::vector<std::vector<int>> vh(n);

// Now iterate over all the elements in the vector
for (auto& v : vh)
{
    // Get the size of the current sub-vector
    size_t size;
    std::cin >> size;

    // Create the vector with size elements
    v = std::vector<int>(size);

    // Read size integers into the vector
    std::copy_n(std::istream_iterator<int>(std::cin), size, begin(v));
}

【讨论】:

  • 也许添加如何直接用元素初始化二维数组:vector&lt;vector&lt;int&gt; &gt;(n, vector&lt;int&gt;(m, 0));
  • @Aziuth 那不一样。在 OP 的代码中,子向量的大小都可以不同。
猜你喜欢
  • 2022-08-07
  • 2020-07-15
  • 2016-05-30
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 2019-09-06
  • 1970-01-01
  • 2021-07-30
相关资源
最近更新 更多