简体   繁体   English

如何正确调整矢量大小?

[英]How to size a vector properly?

From this answer : 这个答案

One place where you can run into a performance issue, is not sizing the vector correctly to begin with. 在一个可能遇到性能问题的地方,没有正确调整向量的大小。

So, how does one size a vector correctly when it is a property of a class? 那么,当它是类的属性时,如何正确地调整向量的大小? Is there a (best) way to set the capacity of vector (at initialisation)? 是否有(最好的)方法来设置向量的容量 (在初始化时)?

Yes there is. 就在这里。 See the reserve method. 请参阅保留方法。 It will request that a vector's capacity be at least enough to contain the number of elements sent as its argument. 它将请求向量的容量至少足以包含作为其参数发送的元素的数量。 If you can anticipate an upper bound on the number of items that you want to store in a vector, then you can reserve that amount of space in your vector. 如果您可以预期要存储在矢量中的项目数的上限,则可以在矢量中保留该空间量。

Example from the above link - 以上链接示例 -

// vector::reserve
#include <iostream>
#include <vector>

int main ()
{
    std::vector<int>::size_type sz;

    std::vector<int> foo;
    sz = foo.capacity();
    std::cout << "making foo grow:\n";
    for (int i=0; i<100; ++i) {
        foo.push_back(i);
        if (sz!=foo.capacity()) {
            sz = foo.capacity();
            std::cout << "capacity changed: " << sz << '\n';
        }
    }

    std::vector<int> bar;
    sz = bar.capacity();
    bar.reserve(100);   // this is the only difference with foo above
    std::cout << "making bar grow:\n";
    for (int i=0; i<100; ++i) {
        bar.push_back(i);

        // This block will execute only once
        if (sz!=bar.capacity()) {
            sz = bar.capacity();
            std::cout << "capacity changed: " << sz << '\n';
        }
    }

    return 0;
}

You will see that as you add more elements to the foo vector, its capacity keeps increasing, but in the second case, since it has already reserved 100 element's space, the capacity is changed only once. 您将看到,当您向foo向量添加更多元素时,其容量会不断增加,但在第二种情况下,由于它已经保留了100个元素的空间,因此容量只会更改一次。

Here is a running example. 是一个运行的例子。

Considering the class is given a value during the constructor the smart thing would be to store an initial size of the vector. 考虑到在构造函数中给类赋值,聪明的东西就是存储向量的初始大小。 Inefficiency comes along when the user is constantly extending the size of the vector as opposed to setting a base length of the vector to begin with. 当用户不断扩展向量的大小而不是设置向量的基本长度时,就会出现低效率。

//consider the vector reads in chars from a string
VecClass::VecCalss(char * str)
{
    size_t LEN = strlen(str);
    Vect = std::vector<char>(LEN, '\0'); //start with the initial size of the char
}

setting an initial size reduces the amount of times a vector is needed to be extended in a program. 设置初始大小减少了在程序中需要扩展向量的次数。

EDIT: or the reserve method would do just about the same, never knew a reserve function existed(pretty handy!). 编辑:或保留方法几乎相同,从来不知道存在保留功能(非常方便!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM