Hi there,

How to set vector size in Class ? I have set vector size at time of daclaration but it does not work. And should we have to deallocate vector memory in destructor ?

#include <iostream>
#include <vector>   //included to use vector

using namespace std;

class VectorDemo
{
    private:

        vector<int> vec(5);      //this does not work

    public:

        VectorDemo()
        {
            //vec input
            for(int index=0; index<vec.size(); index++)
            {
                cout<<"Enter any integer in vector : "<<flush;
                cin >> vec.at(index);
            }
        }

        ~VectorDemo(){}

        void printVectorValues()
        {
            cout<<"Vector values : ";
            for(int index=0; index<vec.size(); index++)
            {
                cout<<vec[index] <<" ";
            }
        }
};

int main()
{
    VectorDemo ob;
    ob.printVectorValues();

    return 0;
}

Anyone please help. Thanks !

i believe you can use reserve() to increase the capacity of a vector. For example...

vector<int> vec(10, 0) // initalize all 10 elements to 0
vec.reserve(20) //reserve more memory for 20 elements in total.

Edited 2 Years Ago by Tycellent

Thanks for reply Tycellent but i need a solution in class. How can i set vector size in class ? Isn't there a way to do that ?

I am testing vector using class for input and output purpose. And I know how to use vectors without using class.

If you have a modern compiler, you can do something like this to initialise class members:

vector<int> vec = vector<int>(5);

Edited 2 Years Ago by Moschops

Thanks Moschops ! :)

Can i set vector size in class constructor using variable ? Actually this is what i need.

This article has been dead for over six months. Start a new discussion instead.