美文网首页
performance of vector in c++

performance of vector in c++

作者: perryn | 来源:发表于2017-08-14 21:39 被阅读28次

    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

    相关文章

      网友评论

          本文标题:performance of vector in c++

          本文链接:https://www.haomeiwen.com/subject/qosprxtx.html