以下两种c ++中的向量使用情况有什么不同?

时间:2016-08-31 16:15:01

标签: c++ vector

案例1:

std::vector< Ticker > snap_tickers_ (n_instruments);

和 案例2:

std::vector< Ticker >snap_tickers_;
snap_tickers_.resize(n_instruments);

我在尝试案例2时遇到编译错误,而在案例1中我没有遇到任何构建失败。这可能与创建矢量的对象类型有关吗?

解答: 在案例2中使用复制构造函数调整大小,该构造函数已被Ticker类删除,因此失败。

2 个答案:

答案 0 :(得分:1)

There is no real difference. case 1:

std::vector<int> vec(5);

allocates 5 int-elements.

case2:

std::vector<int> vec;
vec.resize(5);

here, we begin with an empty vector of ints. When you then call resize, the function checks if the size you passed over is smaller than the actual size (wich is 0, in that case). If yes, allocate _Newsize - size() new elements. If no, pop_back (delete) size() - _Newsize elements.

So in the end, resize is slower, because there are more machine cycles (if statements, subtracting sizes...) to do.

if you want to now more, here's the resize function from vector:

void resize(size_type _Newsize)
        {   // determine new length, padding as needed
        if (_Newsize < size())
            _Pop_back_n(size() - _Newsize);
        else if (size() < _Newsize)
            {   // pad as needed
            _Alty _Alval(this->_Getal());
            _Reserve(_Newsize - size());
            _TRY_BEGIN
            _Uninitialized_default_fill_n(this->_Mylast, _Newsize - size(),
                _Alval);
            _CATCH_ALL
            _Tidy();
            _RERAISE;
            _CATCH_END
            this->_Mylast += _Newsize - size();
            }
        }

as you can see, it does quite a lot. But in the end, it's just a question about (in most cases not important) micro-seconds... So no real difference.

答案 1 :(得分:0)

According to the C++ standard (since C++03), std::vector is required to store all elements contiguously,

[...] which means that elements can be accessed not only through iterators, but also using offsets on regular pointers to elements. This means that a pointer to an element of a vector may be passed to any function that expects a pointer to an element of an array.

Because of this restriction, resizing can potentially slow down performance because of the necessity of copying elements over to a new preallocated block. In practice, this overhead is usually only seen when resizing existing vectors with a lot of items requiring the vector to copy (or move) all of the objects to a new memory location.

In the example you gave, there is no real difference because the original vector had no items in it (and many compilers pre-allocate a chunk of memory to begin). I wouldn't be surprised if the compiler did an optimization to render equivalent code.