std::vector::resize() vs. std::vector::reserve()

后端 未结 6 816
梦谈多话
梦谈多话 2020-11-22 08:21

There is a thread in the comments section in this post about using std::vector::reserve() vs. std::vector::resize().

Here is the original c

6条回答
  •  感动是毒
    2020-11-22 08:54

    It depends on what you want to do. reserve does not add any elements to the vector; it only changes the capacity(), which guarantees that adding elements will not reallocate (and e.g. invalidate iterators). resize adds elements immediately. If you want to add elements later (insert(), push_back()), use reserve. If you want to access elements later (using [] or at()), use resize. So youre MyClass::my_method can be either:

    void MyClass::my_method()
    {
        my_member.clear();
        my_member.reserve( n_dim );
        for ( int k = 0; k < n_dim; ++ k ) {
            my_member.push_back( k );
        }
    }
    

    or

    void MyClass::my_method()
    {
        my_member.resize( n_dim );
        for ( int k = 0; k < n_dim; ++ k ) {
            my_member[k] = k;
        }
    }
    

    Which one you chose is a question of taste, but the code you quote is clearly incorrect.

提交回复
热议问题