【问题标题】:what's wrong with vector::reserve? [duplicate]vector::reserve 有什么问题? [复制]
【发布时间】:2019-12-16 13:35:17
【问题描述】:

我只是想学习 STL 以进行竞争性编程,但我一直在怀疑这个问题! 1. 当我使用 vector::reserve(n) 时,标记为 loop1 和 loop2 的循环不打印任何内容。 2. 但是当我使用 vector::assign(n,0) 我的循环标记为循环 1 和循环 2 工作正常。 为什么会这样?

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
{
    int test;
    scanf("%d", &test);
    while (test > 0) {
        int n;
        scanf("%d", &n);
        vector<int> arr;

        arr.reserve(n);
        //arr.assign(n,0);

        for (int i = 0; i < n; i++) {
            scanf("%d", &arr[i]);
        }

        sort(arr.begin(), arr.end());

        vector<int>::iterator itr;

        // loop1
        for (int x : arr) {
            printf("%d ", x);
        }

        //loop2
        for (itr = arr.begin(); itr != arr.end(); itr++) {
            printf("%d ", *itr);
        }

        test--;
    }

    return 0;
}

【问题讨论】:

  • reserve 不会创建任何元素。它的大小仍然是 0。
  • 你能解释一下吗!而不是投票!我是新手!
  • 嗯,你可以做的第一件事是写一个 3 行的 main 程序,简单地调用(错误地)reserve,看看问题出在哪里。你不需要一个成熟的程序来做这个简单的测试。
  • 请阅读documentation
  • @ShivamKasat 当您遇到问题并正在寻找解决方案时,请将程序减少到重现问题所需的最低限度。通常这会使前进的道路变得清晰,您不必问问题。如果没有好的解决方案出现,那么您可以很好地提出这个问题,因为代码示例中没有噪音。使用minimal reproducible example 作为灵感。

标签: c++ stl iterator


【解决方案1】:

这是一个常见的错误。 std::vector::reserve 不会创建元素或改变容器的大小;你实际上导致了未定义的行为。 reserve 仅更改容量。您正在寻找 std::vector::resize 来更改大小。为了清楚起见,这是一个示例:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> ivec;
    std::cout << ivec.size() << " - " << ivec.capacity() << '\n'; // 0 - 0
    ivec.reserve(100);
    std::cout << ivec.size() << " - " << ivec.capacity() << '\n'; // 0 - 100
    ivec.resize(30);
    std::cout << ivec.size() << " - " << ivec.capacity() << '\n'; // 30 - 100
}

【讨论】:

  • 使用reserve() 的价值在于它消除了在向其添加元素时会发生的向量大小调整。这涉及访问堆以分配更多空间并将向量的元素复制(或移动)到新的更大块,然后删除前一个块。它可以大大加快速度。
【解决方案2】:

vector::reserve 不会改变向量的大小。相反,它只是分配额外的内存,为 push_back 等操作增加向量的容量。

例如:

std::vector<int> v;
// v.size() == 0, v.capacity() == 0
for(int i = 0; i < 100; i++) {
    v.push_back(i); // This will resize the vector a few times
}
// v.size() == 100, v.capacity() >= 100

对比

std::vector<int> v;
v.reserve(100); 
// v.size() == 0, BUT v.capacity() >= 100

for(int i = 0; i < 100; i++) {
    v.push_back(i); // This won't resize the vector now
}

如果要更改矢量的大小,请使用vector::resize

【讨论】:

  • 但是先生,当我尝试访问像这样的元素时 printf("%d",arr[3]);它们可以单独访问!为什么这样?它们要么根本不可访问,要么应通过各种方式访问​​。
猜你喜欢
  • 1970-01-01
  • 2019-03-14
  • 2020-11-15
  • 1970-01-01
  • 2020-09-22
  • 2013-06-18
  • 2012-07-16
相关资源
最近更新 更多