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

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


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


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

int main()
    VectorDemo ob;

    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.

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);

Thanks Moschops ! :)

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

Can i set vector size in class constructor using variable ?