performance of vector in c++

1.many devloper can using vector in c++,but less know how to using vector high performance.if you don't to expand vector of using un running time,you can use vector.reserve (that is a function of vector) to avoid some performance ,you must use it as such rules:

 1. Allocate a new block of memory that is some multiple of the container's current capacity. In most implementations, vector and string capacities grow by a factor of two each time. i.e. their capacity is doubled each time the container must be expanded.
 2. Copy all the elements from the container's old memory into its new memory.
 3. Destroy the objects in the old memory.
 4. Deallocate the old memory.

/*************************************************************************
    > File Name: expance_vector.cc
  > Author: perrynzhou
  > Mail: perrynzhou@gmail.com
  > Created Time: Sat 12 Aug 2017 06:02:21 AM AKDT
 ************************************************************************/

#include <cstdint>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
class FirstVector {
public:
    FirstVector(uint64_t max)
        : m_size(max)
    {
        cout << "FirstVector" << endl;
    }
    void put()
    {
        for (uint64_t i = 0; i < m_size; i++) {
            m_data.push_back(i);
        }
    }

private:
    vector<uint64_t> m_data;
    uint64_t m_size;
};
class SecondVector {
public:
    SecondVector(uint64_t max)
        : m_size(max)
    {
        m_data.reserve(m_size);
        cout << "SecondVector" << endl;
    }
    void put()
    {
        for (uint64_t i = 0; i < m_size; i++) {
            m_data.push_back(i);
        }
    }

private:
    uint64_t m_size;
    vector<uint64_t> m_data;
};
int main(int argc, char* argv[])
{
    if (argc != 3) {
        return -1;
    }
    uint64_t count = atoi(argv[2]);
    if (strncmp(argv[1], "0", 1) == 0) {
        FirstVector fv(count);
        fv.put();
    } else {
        SecondVector sv(count);
        sv.put();
    }
    return 0;
}

runing it ,the result as follows:

Jietu20170814-213849@2x.jpg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容