Initializing vector elements to a particular value

There are 8 constructors for std::vector class, out of which there is this constructor that takes two parameters…

[sourcecode language=”cpp”]vector( size_type _Count,  const Type& _Val );[/sourcecode]

First parameter is size of the vector, second is default value for all elements in the vector.

Let’s suppose you have 1000 Employees in your organization each of them has an initial salary of Rs 8000, we would like to maintain information related to them using a vector. This is how we will be declaring the vector object and initializing every Employee element in it to to have an initial salary of 8000.

[sourcecode language=”cpp”]class Employee
       Employee() : m_Salary( 0 )
       explicit Employee( const int Salary ) : m_Salary( Salary )
       int m_Salary;
};// End class Employee

// Typedefs
typedef Employee Emp;
typedef std::vector EmpVector;

// 1000 employees with salary member variable of every employee instance in
// our vector initialized to 8000
EmpVector EmpVecObj( 1000, Employee( 8000 ));[/sourcecode]

One thought on “Initializing vector elements to a particular value

Appreciate your comments...