Home > C++, VC++ > Initializing vector elements to a particular value

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…

vector( size_type _Count,  const Type& _Val );

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.

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<emp> EmpVector;

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

Categories: C++, VC++ Tags: , ,
  1. shi
    August 8, 2008 at 7:52 pm


    As a complement to these techniques, I think it is interesting to have a look
    at the boost initialization library: http://www.boost.org/doc/libs/1_35_0/libs/assign/doc/index.html

    Best regards,

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: