Create a fixed size std::vector and write to the elements

后端 未结 3 1492
滥情空心
滥情空心 2021-02-19 19:34

In C++ I wish to allocate a fixed-size (but size determined at runtime) std::vector then write to the elements in this vector. This is the code I am using:

int b         


        
3条回答
  •  猫巷女王i
    2021-02-19 19:38

    The direct answer is that you cannot do that: you cannot define the vector as const and then add members to it.

    As others have pointed out, the new standard offers the array class, which is probably more suitable for what you are doing.

    If you are interested in a fixed length, the most related method in vector you can be interested in is reserve(), which will set the vector<> to the size of the given parameter, making vector expansions unnecessary.

    If you cannot use Std C++11, then you need to create a wrapper class that does not let you modify the vector. For example:

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    template 
    class FinalVector {
    public:
        FinalVector(unsigned int size)
            { v.reserve( size ); }
        const T &at(unsigned int i) const
            { return v.at( i ); }
        T &at(unsigned int i)
            { return v.at( i ); }
        T &operator[](unsigned int i)
            { return at( i ); }
        const T &operator[](unsigned int i) const
            { return at( i ); }
        void push_back(const T &x);
        size_t size() const
            { return v.size(); }
        size_t capacity() const
            { return v.size(); }
    private:
        std::vector v;
    };
    
    template
    void FinalVector::push_back(const T &x)
    {
        if ( v.size() < v.capacity() ) {
            v.push_back( x );
        } else {
            throw runtime_error( "vector size exceeded" );
        }
    }
    
    int main()
    {
        FinalVector v( 3 );
    
        v.push_back( 1 );
        v.push_back( 2 );
        v.push_back( 3 );
    
        for(size_t i = 0; i < v.size(); ++i) {
            cout << v[ i ] << endl;
        }
    }
    

    Hope this helps.

提交回复
热议问题