0

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 !

3
Contributors
5
Replies
29
Views
2 Years
Discussion Span
Last Post by Moschops
Featured Replies
  • If you have a modern compiler, you can do something like this to initialise class members: ` vector<int> vec = vector<int>(5); ` Read More

1

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 by Tycellent

0

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.

1

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

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

Edited by Moschops

0

Thanks Moschops ! :)

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.