Cool
Cool

Reputation: 73

Vector class in c++ programing

Can anybody explain me, what is use of vector class? My Professor mentioned about below sentence in the lecture. Template: Each vector has a class parameter that determines which object type will be used by that instance, usually called T. I don't understand what exactly class parameters means?

Upvotes: 3

Views: 552

Answers (4)

Rune FS
Rune FS

Reputation: 21752

The vector is defined as a template like:

template<typename T>
class Vector;

To use it you need to instantiate the template like:

Vector<char> myVector;

Instantiating a vector effectively creates a new class. which is equivalent to what you would get if you'd replaced every occurrence of T in the definition of the template with the class argument (in this case char)

So if we had a simple template

template<typename T>
class DataHolder{ 
public:
 T data
}

Instantiated like:

DataHolder<char> myChar;

Is equivalent to the class:

class DataHolder
{
public:
 char data;
}

Upvotes: 2

JaredPar
JaredPar

Reputation: 755587

The vector type in C++ is essentially a dynamic array. The class parameter is the type of the elements within the vector. For example

int arr[];  // Static C++ array with int elements
vector<int> v; // dynamic array with int elements

In this example int is the class parameter type.

EDIT

As several comments pointed out the choice of "class parameter" by your teacher is misleading. It's more correct to say "template parameter".

Upvotes: 13

Michel de Ruiter
Michel de Ruiter

Reputation: 7966

An example:

std::vector<int> v;

This declares a vector (dynamic array) of int elements. Initially it contains space for zero elements.

The web contains many resources about basic C++. See for example this page for more about STL vectors.

Upvotes: 1

Related Questions